alloc/collections/btree/
map.rs

1use core::borrow::Borrow;
2use core::cmp::Ordering;
3use core::error::Error;
4use core::fmt::{self, Debug};
5use core::hash::{Hash, Hasher};
6use core::iter::{FusedIterator, TrustedLen};
7use core::marker::PhantomData;
8use core::mem::{self, ManuallyDrop};
9use core::ops::{Bound, Index, RangeBounds};
10use core::ptr;
11
12use super::borrow::DormantMutRef;
13use super::dedup_sorted_iter::DedupSortedIter;
14use super::navigate::{LazyLeafRange, LeafRange};
15use super::node::ForceResult::*;
16use super::node::{self, Handle, NodeRef, Root, marker};
17use super::search::SearchBound;
18use super::search::SearchResult::*;
19use super::set_val::SetValZST;
20use crate::alloc::{Allocator, Global};
21use crate::vec::Vec;
22
23mod entry;
24
25use Entry::*;
26#[stable(feature = "rust1", since = "1.0.0")]
27pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
28
29/// Minimum number of elements in a node that is not a root.
30/// We might temporarily have fewer elements during methods.
31pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
32
33// A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
34// - Keys must appear in ascending order (according to the key's type).
35// - Every non-leaf node contains at least 1 element (has at least 2 children).
36// - Every non-root node contains at least MIN_LEN elements.
37//
38// An empty map is represented either by the absence of a root node or by a
39// root node that is an empty leaf.
40
41/// An ordered map based on a [B-Tree].
42///
43/// Given a key type with a [total order], an ordered map stores its entries in key order.
44/// That means that keys must be of a type that implements the [`Ord`] trait,
45/// such that two keys can always be compared to determine their [`Ordering`].
46/// Examples of keys with a total order are strings with lexicographical order,
47/// and numbers with their natural order.
48///
49/// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::into_iter`], [`BTreeMap::values`], or
50/// [`BTreeMap::keys`] produce their items in key order, and take worst-case logarithmic and
51/// amortized constant time per item returned.
52///
53/// It is a logic error for a key to be modified in such a way that the key's ordering relative to
54/// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
55/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
57/// `BTreeMap` that observed the logic error and not result in undefined behavior. This could
58/// include panics, incorrect results, aborts, memory leaks, and non-termination.
59///
60/// # Examples
61///
62/// ```
63/// use std::collections::BTreeMap;
64///
65/// // type inference lets us omit an explicit type signature (which
66/// // would be `BTreeMap<&str, &str>` in this example).
67/// let mut movie_reviews = BTreeMap::new();
68///
69/// // review some movies.
70/// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
71/// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
72/// movie_reviews.insert("The Godfather",      "Very enjoyable.");
73/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
74///
75/// // check for a specific one.
76/// if !movie_reviews.contains_key("Les Misérables") {
77///     println!("We've got {} reviews, but Les Misérables ain't one.",
78///              movie_reviews.len());
79/// }
80///
81/// // oops, this review has a lot of spelling mistakes, let's delete it.
82/// movie_reviews.remove("The Blues Brothers");
83///
84/// // look up the values associated with some keys.
85/// let to_find = ["Up!", "Office Space"];
86/// for movie in &to_find {
87///     match movie_reviews.get(movie) {
88///        Some(review) => println!("{movie}: {review}"),
89///        None => println!("{movie} is unreviewed.")
90///     }
91/// }
92///
93/// // Look up the value for a key (will panic if the key is not found).
94/// println!("Movie review: {}", movie_reviews["Office Space"]);
95///
96/// // iterate over everything.
97/// for (movie, review) in &movie_reviews {
98///     println!("{movie}: \"{review}\"");
99/// }
100/// ```
101///
102/// A `BTreeMap` with a known list of items can be initialized from an array:
103///
104/// ```
105/// use std::collections::BTreeMap;
106///
107/// let solar_distance = BTreeMap::from([
108///     ("Mercury", 0.4),
109///     ("Venus", 0.7),
110///     ("Earth", 1.0),
111///     ("Mars", 1.5),
112/// ]);
113/// ```
114///
115/// ## `Entry` API
116///
117/// `BTreeMap` implements an [`Entry API`], which allows for complex
118/// methods of getting, setting, updating and removing keys and their values:
119///
120/// [`Entry API`]: BTreeMap::entry
121///
122/// ```
123/// use std::collections::BTreeMap;
124///
125/// // type inference lets us omit an explicit type signature (which
126/// // would be `BTreeMap<&str, u8>` in this example).
127/// let mut player_stats = BTreeMap::new();
128///
129/// fn random_stat_buff() -> u8 {
130///     // could actually return some random value here - let's just return
131///     // some fixed value for now
132///     42
133/// }
134///
135/// // insert a key only if it doesn't already exist
136/// player_stats.entry("health").or_insert(100);
137///
138/// // insert a key using a function that provides a new value only if it
139/// // doesn't already exist
140/// player_stats.entry("defence").or_insert_with(random_stat_buff);
141///
142/// // update a key, guarding against the key possibly not being set
143/// let stat = player_stats.entry("attack").or_insert(100);
144/// *stat += random_stat_buff();
145///
146/// // modify an entry before an insert with in-place mutation
147/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
148/// ```
149///
150/// # Background
151///
152/// A B-tree is (like) a [binary search tree], but adapted to the natural granularity that modern
153/// machines like to consume data at. This means that each node contains an entire array of elements,
154/// instead of just a single element.
155///
156/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
157/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
158/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum number of
159/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
160/// is done is *very* inefficient for modern computer architectures. In particular, every element
161/// is stored in its own individually heap-allocated node. This means that every single insertion
162/// triggers a heap-allocation, and every comparison is a potential cache-miss due to the indirection.
163/// Since both heap-allocations and cache-misses are notably expensive in practice, we are forced to,
164/// at the very least, reconsider the BST strategy.
165///
166/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
167/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
168/// searches. However, this does mean that searches will have to do *more* comparisons on average.
169/// The precise number of comparisons depends on the node search strategy used. For optimal cache
170/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
171/// the node using binary search. As a compromise, one could also perform a linear search
172/// that initially only checks every i<sup>th</sup> element for some choice of i.
173///
174/// Currently, our implementation simply performs naive linear search. This provides excellent
175/// performance on *small* nodes of elements which are cheap to compare. However in the future we
176/// would like to further explore choosing the optimal search strategy based on the choice of B,
177/// and possibly other factors. Using linear search, searching for a random element is expected
178/// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
179/// however, performance is excellent.
180///
181/// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
182/// [binary search tree]: https://en.wikipedia.org/wiki/Binary_search_tree
183/// [total order]: https://en.wikipedia.org/wiki/Total_order
184/// [`Cell`]: core::cell::Cell
185/// [`RefCell`]: core::cell::RefCell
186#[stable(feature = "rust1", since = "1.0.0")]
187#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
188#[rustc_insignificant_dtor]
189pub struct BTreeMap<
190    K,
191    V,
192    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
193> {
194    root: Option<Root<K, V>>,
195    length: usize,
196    /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
197    // Although some of the accessory types store a copy of the allocator, the nodes do not.
198    // Because allocations will remain live as long as any copy (like this one) of the allocator
199    // is live, it's unnecessary to store the allocator in each node.
200    pub(super) alloc: ManuallyDrop<A>,
201    // For dropck; the `Box` avoids making the `Unpin` impl more strict than before
202    _marker: PhantomData<crate::boxed::Box<(K, V), A>>,
203}
204
205#[stable(feature = "btree_drop", since = "1.7.0")]
206unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator + Clone> Drop for BTreeMap<K, V, A> {
207    fn drop(&mut self) {
208        drop(unsafe { ptr::read(self) }.into_iter())
209    }
210}
211
212// FIXME: This implementation is "wrong", but changing it would be a breaking change.
213// (The bounds of the automatic `UnwindSafe` implementation have been like this since Rust 1.50.)
214// Maybe we can fix it nonetheless with a crater run, or if the `UnwindSafe`
215// traits are deprecated, or disarmed (no longer causing hard errors) in the future.
216#[stable(feature = "btree_unwindsafe", since = "1.64.0")]
217impl<K, V, A: Allocator + Clone> core::panic::UnwindSafe for BTreeMap<K, V, A>
218where
219    A: core::panic::UnwindSafe,
220    K: core::panic::RefUnwindSafe,
221    V: core::panic::RefUnwindSafe,
222{
223}
224
225#[stable(feature = "rust1", since = "1.0.0")]
226impl<K: Clone, V: Clone, A: Allocator + Clone> Clone for BTreeMap<K, V, A> {
227    fn clone(&self) -> BTreeMap<K, V, A> {
228        fn clone_subtree<'a, K: Clone, V: Clone, A: Allocator + Clone>(
229            node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
230            alloc: A,
231        ) -> BTreeMap<K, V, A>
232        where
233            K: 'a,
234            V: 'a,
235        {
236            match node.force() {
237                Leaf(leaf) => {
238                    let mut out_tree = BTreeMap {
239                        root: Some(Root::new(alloc.clone())),
240                        length: 0,
241                        alloc: ManuallyDrop::new(alloc),
242                        _marker: PhantomData,
243                    };
244
245                    {
246                        let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
247                        let mut out_node = match root.borrow_mut().force() {
248                            Leaf(leaf) => leaf,
249                            Internal(_) => unreachable!(),
250                        };
251
252                        let mut in_edge = leaf.first_edge();
253                        while let Ok(kv) = in_edge.right_kv() {
254                            let (k, v) = kv.into_kv();
255                            in_edge = kv.right_edge();
256
257                            out_node.push(k.clone(), v.clone());
258                            out_tree.length += 1;
259                        }
260                    }
261
262                    out_tree
263                }
264                Internal(internal) => {
265                    let mut out_tree =
266                        clone_subtree(internal.first_edge().descend(), alloc.clone());
267
268                    {
269                        let out_root = out_tree.root.as_mut().unwrap();
270                        let mut out_node = out_root.push_internal_level(alloc.clone());
271                        let mut in_edge = internal.first_edge();
272                        while let Ok(kv) = in_edge.right_kv() {
273                            let (k, v) = kv.into_kv();
274                            in_edge = kv.right_edge();
275
276                            let k = (*k).clone();
277                            let v = (*v).clone();
278                            let subtree = clone_subtree(in_edge.descend(), alloc.clone());
279
280                            // We can't destructure subtree directly
281                            // because BTreeMap implements Drop
282                            let (subroot, sublength) = unsafe {
283                                let subtree = ManuallyDrop::new(subtree);
284                                let root = ptr::read(&subtree.root);
285                                let length = subtree.length;
286                                (root, length)
287                            };
288
289                            out_node.push(
290                                k,
291                                v,
292                                subroot.unwrap_or_else(|| Root::new(alloc.clone())),
293                            );
294                            out_tree.length += 1 + sublength;
295                        }
296                    }
297
298                    out_tree
299                }
300            }
301        }
302
303        if self.is_empty() {
304            BTreeMap::new_in((*self.alloc).clone())
305        } else {
306            clone_subtree(self.root.as_ref().unwrap().reborrow(), (*self.alloc).clone()) // unwrap succeeds because not empty
307        }
308    }
309}
310
311// Internal functionality for `BTreeSet`.
312impl<K, A: Allocator + Clone> BTreeMap<K, SetValZST, A> {
313    pub(super) fn replace(&mut self, key: K) -> Option<K>
314    where
315        K: Ord,
316    {
317        let (map, dormant_map) = DormantMutRef::new(self);
318        let root_node =
319            map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
320        match root_node.search_tree::<K>(&key) {
321            Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
322            GoDown(handle) => {
323                VacantEntry {
324                    key,
325                    handle: Some(handle),
326                    dormant_map,
327                    alloc: (*map.alloc).clone(),
328                    _marker: PhantomData,
329                }
330                .insert(SetValZST);
331                None
332            }
333        }
334    }
335
336    pub(super) fn get_or_insert_with<Q: ?Sized, F>(&mut self, q: &Q, f: F) -> &K
337    where
338        K: Borrow<Q> + Ord,
339        Q: Ord,
340        F: FnOnce(&Q) -> K,
341    {
342        let (map, dormant_map) = DormantMutRef::new(self);
343        let root_node =
344            map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
345        match root_node.search_tree(q) {
346            Found(handle) => handle.into_kv_mut().0,
347            GoDown(handle) => {
348                let key = f(q);
349                assert!(*key.borrow() == *q, "new value is not equal");
350                VacantEntry {
351                    key,
352                    handle: Some(handle),
353                    dormant_map,
354                    alloc: (*map.alloc).clone(),
355                    _marker: PhantomData,
356                }
357                .insert_entry(SetValZST)
358                .into_key()
359            }
360        }
361    }
362}
363
364/// An iterator over the entries of a `BTreeMap`.
365///
366/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
367/// documentation for more.
368///
369/// [`iter`]: BTreeMap::iter
370#[must_use = "iterators are lazy and do nothing unless consumed"]
371#[stable(feature = "rust1", since = "1.0.0")]
372pub struct Iter<'a, K: 'a, V: 'a> {
373    range: LazyLeafRange<marker::Immut<'a>, K, V>,
374    length: usize,
375}
376
377#[stable(feature = "collection_debug", since = "1.17.0")]
378impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        f.debug_list().entries(self.clone()).finish()
381    }
382}
383
384#[stable(feature = "default_iters", since = "1.70.0")]
385impl<'a, K: 'a, V: 'a> Default for Iter<'a, K, V> {
386    /// Creates an empty `btree_map::Iter`.
387    ///
388    /// ```
389    /// # use std::collections::btree_map;
390    /// let iter: btree_map::Iter<'_, u8, u8> = Default::default();
391    /// assert_eq!(iter.len(), 0);
392    /// ```
393    fn default() -> Self {
394        Iter { range: Default::default(), length: 0 }
395    }
396}
397
398/// A mutable iterator over the entries of a `BTreeMap`.
399///
400/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
401/// documentation for more.
402///
403/// [`iter_mut`]: BTreeMap::iter_mut
404#[must_use = "iterators are lazy and do nothing unless consumed"]
405#[stable(feature = "rust1", since = "1.0.0")]
406pub struct IterMut<'a, K: 'a, V: 'a> {
407    range: LazyLeafRange<marker::ValMut<'a>, K, V>,
408    length: usize,
409
410    // Be invariant in `K` and `V`
411    _marker: PhantomData<&'a mut (K, V)>,
412}
413
414#[stable(feature = "collection_debug", since = "1.17.0")]
415impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        let range = Iter { range: self.range.reborrow(), length: self.length };
418        f.debug_list().entries(range).finish()
419    }
420}
421
422#[stable(feature = "default_iters", since = "1.70.0")]
423impl<'a, K: 'a, V: 'a> Default for IterMut<'a, K, V> {
424    /// Creates an empty `btree_map::IterMut`.
425    ///
426    /// ```
427    /// # use std::collections::btree_map;
428    /// let iter: btree_map::IterMut<'_, u8, u8> = Default::default();
429    /// assert_eq!(iter.len(), 0);
430    /// ```
431    fn default() -> Self {
432        IterMut { range: Default::default(), length: 0, _marker: PhantomData {} }
433    }
434}
435
436/// An owning iterator over the entries of a `BTreeMap`, sorted by key.
437///
438/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
439/// (provided by the [`IntoIterator`] trait). See its documentation for more.
440///
441/// [`into_iter`]: IntoIterator::into_iter
442#[stable(feature = "rust1", since = "1.0.0")]
443#[rustc_insignificant_dtor]
444pub struct IntoIter<
445    K,
446    V,
447    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
448> {
449    range: LazyLeafRange<marker::Dying, K, V>,
450    length: usize,
451    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
452    alloc: A,
453}
454
455impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
456    /// Returns an iterator of references over the remaining items.
457    #[inline]
458    pub(super) fn iter(&self) -> Iter<'_, K, V> {
459        Iter { range: self.range.reborrow(), length: self.length }
460    }
461}
462
463#[stable(feature = "collection_debug", since = "1.17.0")]
464impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for IntoIter<K, V, A> {
465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466        f.debug_list().entries(self.iter()).finish()
467    }
468}
469
470#[stable(feature = "default_iters", since = "1.70.0")]
471impl<K, V, A> Default for IntoIter<K, V, A>
472where
473    A: Allocator + Default + Clone,
474{
475    /// Creates an empty `btree_map::IntoIter`.
476    ///
477    /// ```
478    /// # use std::collections::btree_map;
479    /// let iter: btree_map::IntoIter<u8, u8> = Default::default();
480    /// assert_eq!(iter.len(), 0);
481    /// ```
482    fn default() -> Self {
483        IntoIter { range: Default::default(), length: 0, alloc: Default::default() }
484    }
485}
486
487/// An iterator over the keys of a `BTreeMap`.
488///
489/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
490/// documentation for more.
491///
492/// [`keys`]: BTreeMap::keys
493#[must_use = "iterators are lazy and do nothing unless consumed"]
494#[stable(feature = "rust1", since = "1.0.0")]
495pub struct Keys<'a, K, V> {
496    inner: Iter<'a, K, V>,
497}
498
499#[stable(feature = "collection_debug", since = "1.17.0")]
500impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
501    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502        f.debug_list().entries(self.clone()).finish()
503    }
504}
505
506/// An iterator over the values of a `BTreeMap`.
507///
508/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
509/// documentation for more.
510///
511/// [`values`]: BTreeMap::values
512#[must_use = "iterators are lazy and do nothing unless consumed"]
513#[stable(feature = "rust1", since = "1.0.0")]
514pub struct Values<'a, K, V> {
515    inner: Iter<'a, K, V>,
516}
517
518#[stable(feature = "collection_debug", since = "1.17.0")]
519impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
520    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521        f.debug_list().entries(self.clone()).finish()
522    }
523}
524
525/// A mutable iterator over the values of a `BTreeMap`.
526///
527/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
528/// documentation for more.
529///
530/// [`values_mut`]: BTreeMap::values_mut
531#[must_use = "iterators are lazy and do nothing unless consumed"]
532#[stable(feature = "map_values_mut", since = "1.10.0")]
533pub struct ValuesMut<'a, K, V> {
534    inner: IterMut<'a, K, V>,
535}
536
537#[stable(feature = "map_values_mut", since = "1.10.0")]
538impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540        f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
541    }
542}
543
544/// An owning iterator over the keys of a `BTreeMap`.
545///
546/// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
547/// See its documentation for more.
548///
549/// [`into_keys`]: BTreeMap::into_keys
550#[must_use = "iterators are lazy and do nothing unless consumed"]
551#[stable(feature = "map_into_keys_values", since = "1.54.0")]
552pub struct IntoKeys<
553    K,
554    V,
555    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
556> {
557    inner: IntoIter<K, V, A>,
558}
559
560#[stable(feature = "map_into_keys_values", since = "1.54.0")]
561impl<K: fmt::Debug, V, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
562    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563        f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
564    }
565}
566
567/// An owning iterator over the values of a `BTreeMap`.
568///
569/// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
570/// See its documentation for more.
571///
572/// [`into_values`]: BTreeMap::into_values
573#[must_use = "iterators are lazy and do nothing unless consumed"]
574#[stable(feature = "map_into_keys_values", since = "1.54.0")]
575pub struct IntoValues<
576    K,
577    V,
578    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
579> {
580    inner: IntoIter<K, V, A>,
581}
582
583#[stable(feature = "map_into_keys_values", since = "1.54.0")]
584impl<K, V: fmt::Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
585    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586        f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
587    }
588}
589
590/// An iterator over a sub-range of entries in a `BTreeMap`.
591///
592/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
593/// documentation for more.
594///
595/// [`range`]: BTreeMap::range
596#[must_use = "iterators are lazy and do nothing unless consumed"]
597#[stable(feature = "btree_range", since = "1.17.0")]
598pub struct Range<'a, K: 'a, V: 'a> {
599    inner: LeafRange<marker::Immut<'a>, K, V>,
600}
601
602#[stable(feature = "collection_debug", since = "1.17.0")]
603impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
604    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605        f.debug_list().entries(self.clone()).finish()
606    }
607}
608
609/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
610///
611/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
612/// documentation for more.
613///
614/// [`range_mut`]: BTreeMap::range_mut
615#[must_use = "iterators are lazy and do nothing unless consumed"]
616#[stable(feature = "btree_range", since = "1.17.0")]
617pub struct RangeMut<'a, K: 'a, V: 'a> {
618    inner: LeafRange<marker::ValMut<'a>, K, V>,
619
620    // Be invariant in `K` and `V`
621    _marker: PhantomData<&'a mut (K, V)>,
622}
623
624#[stable(feature = "collection_debug", since = "1.17.0")]
625impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627        let range = Range { inner: self.inner.reborrow() };
628        f.debug_list().entries(range).finish()
629    }
630}
631
632impl<K, V> BTreeMap<K, V> {
633    /// Makes a new, empty `BTreeMap`.
634    ///
635    /// Does not allocate anything on its own.
636    ///
637    /// # Examples
638    ///
639    /// ```
640    /// use std::collections::BTreeMap;
641    ///
642    /// let mut map = BTreeMap::new();
643    ///
644    /// // entries can now be inserted into the empty map
645    /// map.insert(1, "a");
646    /// ```
647    #[stable(feature = "rust1", since = "1.0.0")]
648    #[rustc_const_stable(feature = "const_btree_new", since = "1.66.0")]
649    #[inline]
650    #[must_use]
651    pub const fn new() -> BTreeMap<K, V> {
652        BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(Global), _marker: PhantomData }
653    }
654}
655
656impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
657    /// Clears the map, removing all elements.
658    ///
659    /// # Examples
660    ///
661    /// ```
662    /// use std::collections::BTreeMap;
663    ///
664    /// let mut a = BTreeMap::new();
665    /// a.insert(1, "a");
666    /// a.clear();
667    /// assert!(a.is_empty());
668    /// ```
669    #[stable(feature = "rust1", since = "1.0.0")]
670    pub fn clear(&mut self) {
671        // avoid moving the allocator
672        drop(BTreeMap {
673            root: mem::replace(&mut self.root, None),
674            length: mem::replace(&mut self.length, 0),
675            alloc: self.alloc.clone(),
676            _marker: PhantomData,
677        });
678    }
679
680    /// Makes a new empty BTreeMap with a reasonable choice for B.
681    ///
682    /// # Examples
683    ///
684    /// ```
685    /// # #![feature(allocator_api)]
686    /// # #![feature(btreemap_alloc)]
687    /// use std::collections::BTreeMap;
688    /// use std::alloc::Global;
689    ///
690    /// let mut map = BTreeMap::new_in(Global);
691    ///
692    /// // entries can now be inserted into the empty map
693    /// map.insert(1, "a");
694    /// ```
695    #[unstable(feature = "btreemap_alloc", issue = "32838")]
696    pub const fn new_in(alloc: A) -> BTreeMap<K, V, A> {
697        BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
698    }
699}
700
701impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
702    /// Returns a reference to the value corresponding to the key.
703    ///
704    /// The key may be any borrowed form of the map's key type, but the ordering
705    /// on the borrowed form *must* match the ordering on the key type.
706    ///
707    /// # Examples
708    ///
709    /// ```
710    /// use std::collections::BTreeMap;
711    ///
712    /// let mut map = BTreeMap::new();
713    /// map.insert(1, "a");
714    /// assert_eq!(map.get(&1), Some(&"a"));
715    /// assert_eq!(map.get(&2), None);
716    /// ```
717    #[stable(feature = "rust1", since = "1.0.0")]
718    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
719    where
720        K: Borrow<Q> + Ord,
721        Q: Ord,
722    {
723        let root_node = self.root.as_ref()?.reborrow();
724        match root_node.search_tree(key) {
725            Found(handle) => Some(handle.into_kv().1),
726            GoDown(_) => None,
727        }
728    }
729
730    /// Returns the key-value pair corresponding to the supplied key. This is
731    /// potentially useful:
732    /// - for key types where non-identical keys can be considered equal;
733    /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
734    /// - for getting a reference to a key with the same lifetime as the collection.
735    ///
736    /// The supplied key may be any borrowed form of the map's key type, but the ordering
737    /// on the borrowed form *must* match the ordering on the key type.
738    ///
739    /// # Examples
740    ///
741    /// ```
742    /// use std::cmp::Ordering;
743    /// use std::collections::BTreeMap;
744    ///
745    /// #[derive(Clone, Copy, Debug)]
746    /// struct S {
747    ///     id: u32,
748    /// #   #[allow(unused)] // prevents a "field `name` is never read" error
749    ///     name: &'static str, // ignored by equality and ordering operations
750    /// }
751    ///
752    /// impl PartialEq for S {
753    ///     fn eq(&self, other: &S) -> bool {
754    ///         self.id == other.id
755    ///     }
756    /// }
757    ///
758    /// impl Eq for S {}
759    ///
760    /// impl PartialOrd for S {
761    ///     fn partial_cmp(&self, other: &S) -> Option<Ordering> {
762    ///         self.id.partial_cmp(&other.id)
763    ///     }
764    /// }
765    ///
766    /// impl Ord for S {
767    ///     fn cmp(&self, other: &S) -> Ordering {
768    ///         self.id.cmp(&other.id)
769    ///     }
770    /// }
771    ///
772    /// let j_a = S { id: 1, name: "Jessica" };
773    /// let j_b = S { id: 1, name: "Jess" };
774    /// let p = S { id: 2, name: "Paul" };
775    /// assert_eq!(j_a, j_b);
776    ///
777    /// let mut map = BTreeMap::new();
778    /// map.insert(j_a, "Paris");
779    /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
780    /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
781    /// assert_eq!(map.get_key_value(&p), None);
782    /// ```
783    #[stable(feature = "map_get_key_value", since = "1.40.0")]
784    pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
785    where
786        K: Borrow<Q> + Ord,
787        Q: Ord,
788    {
789        let root_node = self.root.as_ref()?.reborrow();
790        match root_node.search_tree(k) {
791            Found(handle) => Some(handle.into_kv()),
792            GoDown(_) => None,
793        }
794    }
795
796    /// Returns the first key-value pair in the map.
797    /// The key in this pair is the minimum key in the map.
798    ///
799    /// # Examples
800    ///
801    /// ```
802    /// use std::collections::BTreeMap;
803    ///
804    /// let mut map = BTreeMap::new();
805    /// assert_eq!(map.first_key_value(), None);
806    /// map.insert(1, "b");
807    /// map.insert(2, "a");
808    /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
809    /// ```
810    #[stable(feature = "map_first_last", since = "1.66.0")]
811    pub fn first_key_value(&self) -> Option<(&K, &V)>
812    where
813        K: Ord,
814    {
815        let root_node = self.root.as_ref()?.reborrow();
816        root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
817    }
818
819    /// Returns the first entry in the map for in-place manipulation.
820    /// The key of this entry is the minimum key in the map.
821    ///
822    /// # Examples
823    ///
824    /// ```
825    /// use std::collections::BTreeMap;
826    ///
827    /// let mut map = BTreeMap::new();
828    /// map.insert(1, "a");
829    /// map.insert(2, "b");
830    /// if let Some(mut entry) = map.first_entry() {
831    ///     if *entry.key() > 0 {
832    ///         entry.insert("first");
833    ///     }
834    /// }
835    /// assert_eq!(*map.get(&1).unwrap(), "first");
836    /// assert_eq!(*map.get(&2).unwrap(), "b");
837    /// ```
838    #[stable(feature = "map_first_last", since = "1.66.0")]
839    pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
840    where
841        K: Ord,
842    {
843        let (map, dormant_map) = DormantMutRef::new(self);
844        let root_node = map.root.as_mut()?.borrow_mut();
845        let kv = root_node.first_leaf_edge().right_kv().ok()?;
846        Some(OccupiedEntry {
847            handle: kv.forget_node_type(),
848            dormant_map,
849            alloc: (*map.alloc).clone(),
850            _marker: PhantomData,
851        })
852    }
853
854    /// Removes and returns the first element in the map.
855    /// The key of this element is the minimum key that was in the map.
856    ///
857    /// # Examples
858    ///
859    /// Draining elements in ascending order, while keeping a usable map each iteration.
860    ///
861    /// ```
862    /// use std::collections::BTreeMap;
863    ///
864    /// let mut map = BTreeMap::new();
865    /// map.insert(1, "a");
866    /// map.insert(2, "b");
867    /// while let Some((key, _val)) = map.pop_first() {
868    ///     assert!(map.iter().all(|(k, _v)| *k > key));
869    /// }
870    /// assert!(map.is_empty());
871    /// ```
872    #[stable(feature = "map_first_last", since = "1.66.0")]
873    pub fn pop_first(&mut self) -> Option<(K, V)>
874    where
875        K: Ord,
876    {
877        self.first_entry().map(|entry| entry.remove_entry())
878    }
879
880    /// Returns the last key-value pair in the map.
881    /// The key in this pair is the maximum key in the map.
882    ///
883    /// # Examples
884    ///
885    /// ```
886    /// use std::collections::BTreeMap;
887    ///
888    /// let mut map = BTreeMap::new();
889    /// map.insert(1, "b");
890    /// map.insert(2, "a");
891    /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
892    /// ```
893    #[stable(feature = "map_first_last", since = "1.66.0")]
894    pub fn last_key_value(&self) -> Option<(&K, &V)>
895    where
896        K: Ord,
897    {
898        let root_node = self.root.as_ref()?.reborrow();
899        root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
900    }
901
902    /// Returns the last entry in the map for in-place manipulation.
903    /// The key of this entry is the maximum key in the map.
904    ///
905    /// # Examples
906    ///
907    /// ```
908    /// use std::collections::BTreeMap;
909    ///
910    /// let mut map = BTreeMap::new();
911    /// map.insert(1, "a");
912    /// map.insert(2, "b");
913    /// if let Some(mut entry) = map.last_entry() {
914    ///     if *entry.key() > 0 {
915    ///         entry.insert("last");
916    ///     }
917    /// }
918    /// assert_eq!(*map.get(&1).unwrap(), "a");
919    /// assert_eq!(*map.get(&2).unwrap(), "last");
920    /// ```
921    #[stable(feature = "map_first_last", since = "1.66.0")]
922    pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
923    where
924        K: Ord,
925    {
926        let (map, dormant_map) = DormantMutRef::new(self);
927        let root_node = map.root.as_mut()?.borrow_mut();
928        let kv = root_node.last_leaf_edge().left_kv().ok()?;
929        Some(OccupiedEntry {
930            handle: kv.forget_node_type(),
931            dormant_map,
932            alloc: (*map.alloc).clone(),
933            _marker: PhantomData,
934        })
935    }
936
937    /// Removes and returns the last element in the map.
938    /// The key of this element is the maximum key that was in the map.
939    ///
940    /// # Examples
941    ///
942    /// Draining elements in descending order, while keeping a usable map each iteration.
943    ///
944    /// ```
945    /// use std::collections::BTreeMap;
946    ///
947    /// let mut map = BTreeMap::new();
948    /// map.insert(1, "a");
949    /// map.insert(2, "b");
950    /// while let Some((key, _val)) = map.pop_last() {
951    ///     assert!(map.iter().all(|(k, _v)| *k < key));
952    /// }
953    /// assert!(map.is_empty());
954    /// ```
955    #[stable(feature = "map_first_last", since = "1.66.0")]
956    pub fn pop_last(&mut self) -> Option<(K, V)>
957    where
958        K: Ord,
959    {
960        self.last_entry().map(|entry| entry.remove_entry())
961    }
962
963    /// Returns `true` if the map contains a value for the specified key.
964    ///
965    /// The key may be any borrowed form of the map's key type, but the ordering
966    /// on the borrowed form *must* match the ordering on the key type.
967    ///
968    /// # Examples
969    ///
970    /// ```
971    /// use std::collections::BTreeMap;
972    ///
973    /// let mut map = BTreeMap::new();
974    /// map.insert(1, "a");
975    /// assert_eq!(map.contains_key(&1), true);
976    /// assert_eq!(map.contains_key(&2), false);
977    /// ```
978    #[stable(feature = "rust1", since = "1.0.0")]
979    #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_contains_key")]
980    pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
981    where
982        K: Borrow<Q> + Ord,
983        Q: Ord,
984    {
985        self.get(key).is_some()
986    }
987
988    /// Returns a mutable reference to the value corresponding to the key.
989    ///
990    /// The key may be any borrowed form of the map's key type, but the ordering
991    /// on the borrowed form *must* match the ordering on the key type.
992    ///
993    /// # Examples
994    ///
995    /// ```
996    /// use std::collections::BTreeMap;
997    ///
998    /// let mut map = BTreeMap::new();
999    /// map.insert(1, "a");
1000    /// if let Some(x) = map.get_mut(&1) {
1001    ///     *x = "b";
1002    /// }
1003    /// assert_eq!(map[&1], "b");
1004    /// ```
1005    // See `get` for implementation notes, this is basically a copy-paste with mut's added
1006    #[stable(feature = "rust1", since = "1.0.0")]
1007    pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
1008    where
1009        K: Borrow<Q> + Ord,
1010        Q: Ord,
1011    {
1012        let root_node = self.root.as_mut()?.borrow_mut();
1013        match root_node.search_tree(key) {
1014            Found(handle) => Some(handle.into_val_mut()),
1015            GoDown(_) => None,
1016        }
1017    }
1018
1019    /// Inserts a key-value pair into the map.
1020    ///
1021    /// If the map did not have this key present, `None` is returned.
1022    ///
1023    /// If the map did have this key present, the value is updated, and the old
1024    /// value is returned. The key is not updated, though; this matters for
1025    /// types that can be `==` without being identical. See the [module-level
1026    /// documentation] for more.
1027    ///
1028    /// [module-level documentation]: index.html#insert-and-complex-keys
1029    ///
1030    /// # Examples
1031    ///
1032    /// ```
1033    /// use std::collections::BTreeMap;
1034    ///
1035    /// let mut map = BTreeMap::new();
1036    /// assert_eq!(map.insert(37, "a"), None);
1037    /// assert_eq!(map.is_empty(), false);
1038    ///
1039    /// map.insert(37, "b");
1040    /// assert_eq!(map.insert(37, "c"), Some("b"));
1041    /// assert_eq!(map[&37], "c");
1042    /// ```
1043    #[stable(feature = "rust1", since = "1.0.0")]
1044    #[rustc_confusables("push", "put", "set")]
1045    #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_insert")]
1046    pub fn insert(&mut self, key: K, value: V) -> Option<V>
1047    where
1048        K: Ord,
1049    {
1050        match self.entry(key) {
1051            Occupied(mut entry) => Some(entry.insert(value)),
1052            Vacant(entry) => {
1053                entry.insert(value);
1054                None
1055            }
1056        }
1057    }
1058
1059    /// Tries to insert a key-value pair into the map, and returns
1060    /// a mutable reference to the value in the entry.
1061    ///
1062    /// If the map already had this key present, nothing is updated, and
1063    /// an error containing the occupied entry and the value is returned.
1064    ///
1065    /// # Examples
1066    ///
1067    /// ```
1068    /// #![feature(map_try_insert)]
1069    ///
1070    /// use std::collections::BTreeMap;
1071    ///
1072    /// let mut map = BTreeMap::new();
1073    /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1074    ///
1075    /// let err = map.try_insert(37, "b").unwrap_err();
1076    /// assert_eq!(err.entry.key(), &37);
1077    /// assert_eq!(err.entry.get(), &"a");
1078    /// assert_eq!(err.value, "b");
1079    /// ```
1080    #[unstable(feature = "map_try_insert", issue = "82766")]
1081    pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
1082    where
1083        K: Ord,
1084    {
1085        match self.entry(key) {
1086            Occupied(entry) => Err(OccupiedError { entry, value }),
1087            Vacant(entry) => Ok(entry.insert(value)),
1088        }
1089    }
1090
1091    /// Removes a key from the map, returning the value at the key if the key
1092    /// was previously in the map.
1093    ///
1094    /// The key may be any borrowed form of the map's key type, but the ordering
1095    /// on the borrowed form *must* match the ordering on the key type.
1096    ///
1097    /// # Examples
1098    ///
1099    /// ```
1100    /// use std::collections::BTreeMap;
1101    ///
1102    /// let mut map = BTreeMap::new();
1103    /// map.insert(1, "a");
1104    /// assert_eq!(map.remove(&1), Some("a"));
1105    /// assert_eq!(map.remove(&1), None);
1106    /// ```
1107    #[stable(feature = "rust1", since = "1.0.0")]
1108    #[rustc_confusables("delete", "take")]
1109    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1110    where
1111        K: Borrow<Q> + Ord,
1112        Q: Ord,
1113    {
1114        self.remove_entry(key).map(|(_, v)| v)
1115    }
1116
1117    /// Removes a key from the map, returning the stored key and value if the key
1118    /// was previously in the map.
1119    ///
1120    /// The key may be any borrowed form of the map's key type, but the ordering
1121    /// on the borrowed form *must* match the ordering on the key type.
1122    ///
1123    /// # Examples
1124    ///
1125    /// ```
1126    /// use std::collections::BTreeMap;
1127    ///
1128    /// let mut map = BTreeMap::new();
1129    /// map.insert(1, "a");
1130    /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1131    /// assert_eq!(map.remove_entry(&1), None);
1132    /// ```
1133    #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1134    pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1135    where
1136        K: Borrow<Q> + Ord,
1137        Q: Ord,
1138    {
1139        let (map, dormant_map) = DormantMutRef::new(self);
1140        let root_node = map.root.as_mut()?.borrow_mut();
1141        match root_node.search_tree(key) {
1142            Found(handle) => Some(
1143                OccupiedEntry {
1144                    handle,
1145                    dormant_map,
1146                    alloc: (*map.alloc).clone(),
1147                    _marker: PhantomData,
1148                }
1149                .remove_entry(),
1150            ),
1151            GoDown(_) => None,
1152        }
1153    }
1154
1155    /// Retains only the elements specified by the predicate.
1156    ///
1157    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1158    /// The elements are visited in ascending key order.
1159    ///
1160    /// # Examples
1161    ///
1162    /// ```
1163    /// use std::collections::BTreeMap;
1164    ///
1165    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1166    /// // Keep only the elements with even-numbered keys.
1167    /// map.retain(|&k, _| k % 2 == 0);
1168    /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1169    /// ```
1170    #[inline]
1171    #[stable(feature = "btree_retain", since = "1.53.0")]
1172    pub fn retain<F>(&mut self, mut f: F)
1173    where
1174        K: Ord,
1175        F: FnMut(&K, &mut V) -> bool,
1176    {
1177        self.extract_if(.., |k, v| !f(k, v)).for_each(drop);
1178    }
1179
1180    /// Moves all elements from `other` into `self`, leaving `other` empty.
1181    ///
1182    /// If a key from `other` is already present in `self`, the respective
1183    /// value from `self` will be overwritten with the respective value from `other`.
1184    /// Similar to [`insert`], though, the key is not overwritten,
1185    /// which matters for types that can be `==` without being identical.
1186    ///
1187    /// [`insert`]: BTreeMap::insert
1188    ///
1189    /// # Examples
1190    ///
1191    /// ```
1192    /// use std::collections::BTreeMap;
1193    ///
1194    /// let mut a = BTreeMap::new();
1195    /// a.insert(1, "a");
1196    /// a.insert(2, "b");
1197    /// a.insert(3, "c"); // Note: Key (3) also present in b.
1198    ///
1199    /// let mut b = BTreeMap::new();
1200    /// b.insert(3, "d"); // Note: Key (3) also present in a.
1201    /// b.insert(4, "e");
1202    /// b.insert(5, "f");
1203    ///
1204    /// a.append(&mut b);
1205    ///
1206    /// assert_eq!(a.len(), 5);
1207    /// assert_eq!(b.len(), 0);
1208    ///
1209    /// assert_eq!(a[&1], "a");
1210    /// assert_eq!(a[&2], "b");
1211    /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
1212    /// assert_eq!(a[&4], "e");
1213    /// assert_eq!(a[&5], "f");
1214    /// ```
1215    #[stable(feature = "btree_append", since = "1.11.0")]
1216    pub fn append(&mut self, other: &mut Self)
1217    where
1218        K: Ord,
1219        A: Clone,
1220    {
1221        // Do we have to append anything at all?
1222        if other.is_empty() {
1223            return;
1224        }
1225
1226        // We can just swap `self` and `other` if `self` is empty.
1227        if self.is_empty() {
1228            mem::swap(self, other);
1229            return;
1230        }
1231
1232        let self_iter = mem::replace(self, Self::new_in((*self.alloc).clone())).into_iter();
1233        let other_iter = mem::replace(other, Self::new_in((*self.alloc).clone())).into_iter();
1234        let root = self.root.get_or_insert_with(|| Root::new((*self.alloc).clone()));
1235        root.append_from_sorted_iters(
1236            self_iter,
1237            other_iter,
1238            &mut self.length,
1239            (*self.alloc).clone(),
1240        )
1241    }
1242
1243    /// Constructs a double-ended iterator over a sub-range of elements in the map.
1244    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1245    /// yield elements from min (inclusive) to max (exclusive).
1246    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1247    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1248    /// range from 4 to 10.
1249    ///
1250    /// # Panics
1251    ///
1252    /// Panics if range `start > end`.
1253    /// Panics if range `start == end` and both bounds are `Excluded`.
1254    ///
1255    /// # Examples
1256    ///
1257    /// ```
1258    /// use std::collections::BTreeMap;
1259    /// use std::ops::Bound::Included;
1260    ///
1261    /// let mut map = BTreeMap::new();
1262    /// map.insert(3, "a");
1263    /// map.insert(5, "b");
1264    /// map.insert(8, "c");
1265    /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1266    ///     println!("{key}: {value}");
1267    /// }
1268    /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1269    /// ```
1270    #[stable(feature = "btree_range", since = "1.17.0")]
1271    pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1272    where
1273        T: Ord,
1274        K: Borrow<T> + Ord,
1275        R: RangeBounds<T>,
1276    {
1277        if let Some(root) = &self.root {
1278            Range { inner: root.reborrow().range_search(range) }
1279        } else {
1280            Range { inner: LeafRange::none() }
1281        }
1282    }
1283
1284    /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1285    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1286    /// yield elements from min (inclusive) to max (exclusive).
1287    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1288    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1289    /// range from 4 to 10.
1290    ///
1291    /// # Panics
1292    ///
1293    /// Panics if range `start > end`.
1294    /// Panics if range `start == end` and both bounds are `Excluded`.
1295    ///
1296    /// # Examples
1297    ///
1298    /// ```
1299    /// use std::collections::BTreeMap;
1300    ///
1301    /// let mut map: BTreeMap<&str, i32> =
1302    ///     [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1303    /// for (_, balance) in map.range_mut("B".."Cheryl") {
1304    ///     *balance += 100;
1305    /// }
1306    /// for (name, balance) in &map {
1307    ///     println!("{name} => {balance}");
1308    /// }
1309    /// ```
1310    #[stable(feature = "btree_range", since = "1.17.0")]
1311    pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1312    where
1313        T: Ord,
1314        K: Borrow<T> + Ord,
1315        R: RangeBounds<T>,
1316    {
1317        if let Some(root) = &mut self.root {
1318            RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1319        } else {
1320            RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1321        }
1322    }
1323
1324    /// Gets the given key's corresponding entry in the map for in-place manipulation.
1325    ///
1326    /// # Examples
1327    ///
1328    /// ```
1329    /// use std::collections::BTreeMap;
1330    ///
1331    /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1332    ///
1333    /// // count the number of occurrences of letters in the vec
1334    /// for x in ["a", "b", "a", "c", "a", "b"] {
1335    ///     count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1336    /// }
1337    ///
1338    /// assert_eq!(count["a"], 3);
1339    /// assert_eq!(count["b"], 2);
1340    /// assert_eq!(count["c"], 1);
1341    /// ```
1342    #[stable(feature = "rust1", since = "1.0.0")]
1343    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1344    where
1345        K: Ord,
1346    {
1347        let (map, dormant_map) = DormantMutRef::new(self);
1348        match map.root {
1349            None => Vacant(VacantEntry {
1350                key,
1351                handle: None,
1352                dormant_map,
1353                alloc: (*map.alloc).clone(),
1354                _marker: PhantomData,
1355            }),
1356            Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1357                Found(handle) => Occupied(OccupiedEntry {
1358                    handle,
1359                    dormant_map,
1360                    alloc: (*map.alloc).clone(),
1361                    _marker: PhantomData,
1362                }),
1363                GoDown(handle) => Vacant(VacantEntry {
1364                    key,
1365                    handle: Some(handle),
1366                    dormant_map,
1367                    alloc: (*map.alloc).clone(),
1368                    _marker: PhantomData,
1369                }),
1370            },
1371        }
1372    }
1373
1374    /// Splits the collection into two at the given key. Returns everything after the given key,
1375    /// including the key. If the key is not present, the split will occur at the nearest
1376    /// greater key, or return an empty map if no such key exists.
1377    ///
1378    /// # Examples
1379    ///
1380    /// ```
1381    /// use std::collections::BTreeMap;
1382    ///
1383    /// let mut a = BTreeMap::new();
1384    /// a.insert(1, "a");
1385    /// a.insert(2, "b");
1386    /// a.insert(3, "c");
1387    /// a.insert(17, "d");
1388    /// a.insert(41, "e");
1389    ///
1390    /// let b = a.split_off(&3);
1391    ///
1392    /// assert_eq!(a.len(), 2);
1393    /// assert_eq!(b.len(), 3);
1394    ///
1395    /// assert_eq!(a[&1], "a");
1396    /// assert_eq!(a[&2], "b");
1397    ///
1398    /// assert_eq!(b[&3], "c");
1399    /// assert_eq!(b[&17], "d");
1400    /// assert_eq!(b[&41], "e");
1401    /// ```
1402    #[stable(feature = "btree_split_off", since = "1.11.0")]
1403    pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1404    where
1405        K: Borrow<Q> + Ord,
1406        A: Clone,
1407    {
1408        if self.is_empty() {
1409            return Self::new_in((*self.alloc).clone());
1410        }
1411
1412        let total_num = self.len();
1413        let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1414
1415        let right_root = left_root.split_off(key, (*self.alloc).clone());
1416
1417        let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1418        self.length = new_left_len;
1419
1420        BTreeMap {
1421            root: Some(right_root),
1422            length: right_len,
1423            alloc: self.alloc.clone(),
1424            _marker: PhantomData,
1425        }
1426    }
1427
1428    /// Creates an iterator that visits elements (key-value pairs) in the specified range in
1429    /// ascending key order and uses a closure to determine if an element
1430    /// should be removed.
1431    ///
1432    /// If the closure returns `true`, the element is removed from the map and
1433    /// yielded. If the closure returns `false`, or panics, the element remains
1434    /// in the map and will not be yielded.
1435    ///
1436    /// The iterator also lets you mutate the value of each element in the
1437    /// closure, regardless of whether you choose to keep or remove it.
1438    ///
1439    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1440    /// or the iteration short-circuits, then the remaining elements will be retained.
1441    /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
1442    /// or [`retain`] with a negated predicate if you also do not need to restrict the range.
1443    ///
1444    /// [`retain`]: BTreeMap::retain
1445    ///
1446    /// # Examples
1447    ///
1448    /// ```
1449    /// use std::collections::BTreeMap;
1450    ///
1451    /// // Splitting a map into even and odd keys, reusing the original map:
1452    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1453    /// let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
1454    /// let odds = map;
1455    /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1456    /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1457    ///
1458    /// // Splitting a map into low and high halves, reusing the original map:
1459    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1460    /// let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect();
1461    /// let high = map;
1462    /// assert_eq!(low.keys().copied().collect::<Vec<_>>(), [0, 1, 2, 3]);
1463    /// assert_eq!(high.keys().copied().collect::<Vec<_>>(), [4, 5, 6, 7]);
1464    /// ```
1465    #[stable(feature = "btree_extract_if", since = "1.91.0")]
1466    pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, R, F, A>
1467    where
1468        K: Ord,
1469        R: RangeBounds<K>,
1470        F: FnMut(&K, &mut V) -> bool,
1471    {
1472        let (inner, alloc) = self.extract_if_inner(range);
1473        ExtractIf { pred, inner, alloc }
1474    }
1475
1476    pub(super) fn extract_if_inner<R>(&mut self, range: R) -> (ExtractIfInner<'_, K, V, R>, A)
1477    where
1478        K: Ord,
1479        R: RangeBounds<K>,
1480    {
1481        if let Some(root) = self.root.as_mut() {
1482            let (root, dormant_root) = DormantMutRef::new(root);
1483            let first = root.borrow_mut().lower_bound(SearchBound::from_range(range.start_bound()));
1484            (
1485                ExtractIfInner {
1486                    length: &mut self.length,
1487                    dormant_root: Some(dormant_root),
1488                    cur_leaf_edge: Some(first),
1489                    range,
1490                },
1491                (*self.alloc).clone(),
1492            )
1493        } else {
1494            (
1495                ExtractIfInner {
1496                    length: &mut self.length,
1497                    dormant_root: None,
1498                    cur_leaf_edge: None,
1499                    range,
1500                },
1501                (*self.alloc).clone(),
1502            )
1503        }
1504    }
1505
1506    /// Creates a consuming iterator visiting all the keys, in sorted order.
1507    /// The map cannot be used after calling this.
1508    /// The iterator element type is `K`.
1509    ///
1510    /// # Examples
1511    ///
1512    /// ```
1513    /// use std::collections::BTreeMap;
1514    ///
1515    /// let mut a = BTreeMap::new();
1516    /// a.insert(2, "b");
1517    /// a.insert(1, "a");
1518    ///
1519    /// let keys: Vec<i32> = a.into_keys().collect();
1520    /// assert_eq!(keys, [1, 2]);
1521    /// ```
1522    #[inline]
1523    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1524    pub fn into_keys(self) -> IntoKeys<K, V, A> {
1525        IntoKeys { inner: self.into_iter() }
1526    }
1527
1528    /// Creates a consuming iterator visiting all the values, in order by key.
1529    /// The map cannot be used after calling this.
1530    /// The iterator element type is `V`.
1531    ///
1532    /// # Examples
1533    ///
1534    /// ```
1535    /// use std::collections::BTreeMap;
1536    ///
1537    /// let mut a = BTreeMap::new();
1538    /// a.insert(1, "hello");
1539    /// a.insert(2, "goodbye");
1540    ///
1541    /// let values: Vec<&str> = a.into_values().collect();
1542    /// assert_eq!(values, ["hello", "goodbye"]);
1543    /// ```
1544    #[inline]
1545    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1546    pub fn into_values(self) -> IntoValues<K, V, A> {
1547        IntoValues { inner: self.into_iter() }
1548    }
1549
1550    /// Makes a `BTreeMap` from a sorted iterator.
1551    pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1552    where
1553        K: Ord,
1554        I: IntoIterator<Item = (K, V)>,
1555    {
1556        let mut root = Root::new(alloc.clone());
1557        let mut length = 0;
1558        root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1559        BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
1560    }
1561}
1562
1563#[stable(feature = "rust1", since = "1.0.0")]
1564impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, A> {
1565    type Item = (&'a K, &'a V);
1566    type IntoIter = Iter<'a, K, V>;
1567
1568    fn into_iter(self) -> Iter<'a, K, V> {
1569        self.iter()
1570    }
1571}
1572
1573#[stable(feature = "rust1", since = "1.0.0")]
1574impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1575    type Item = (&'a K, &'a V);
1576
1577    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1578        if self.length == 0 {
1579            None
1580        } else {
1581            self.length -= 1;
1582            Some(unsafe { self.range.next_unchecked() })
1583        }
1584    }
1585
1586    fn size_hint(&self) -> (usize, Option<usize>) {
1587        (self.length, Some(self.length))
1588    }
1589
1590    fn last(mut self) -> Option<(&'a K, &'a V)> {
1591        self.next_back()
1592    }
1593
1594    fn min(mut self) -> Option<(&'a K, &'a V)>
1595    where
1596        (&'a K, &'a V): Ord,
1597    {
1598        self.next()
1599    }
1600
1601    fn max(mut self) -> Option<(&'a K, &'a V)>
1602    where
1603        (&'a K, &'a V): Ord,
1604    {
1605        self.next_back()
1606    }
1607}
1608
1609#[stable(feature = "fused", since = "1.26.0")]
1610impl<K, V> FusedIterator for Iter<'_, K, V> {}
1611
1612#[stable(feature = "rust1", since = "1.0.0")]
1613impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1614    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1615        if self.length == 0 {
1616            None
1617        } else {
1618            self.length -= 1;
1619            Some(unsafe { self.range.next_back_unchecked() })
1620        }
1621    }
1622}
1623
1624#[stable(feature = "rust1", since = "1.0.0")]
1625impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1626    fn len(&self) -> usize {
1627        self.length
1628    }
1629}
1630
1631#[unstable(feature = "trusted_len", issue = "37572")]
1632unsafe impl<K, V> TrustedLen for Iter<'_, K, V> {}
1633
1634#[stable(feature = "rust1", since = "1.0.0")]
1635impl<K, V> Clone for Iter<'_, K, V> {
1636    fn clone(&self) -> Self {
1637        Iter { range: self.range.clone(), length: self.length }
1638    }
1639}
1640
1641#[stable(feature = "rust1", since = "1.0.0")]
1642impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1643    type Item = (&'a K, &'a mut V);
1644    type IntoIter = IterMut<'a, K, V>;
1645
1646    fn into_iter(self) -> IterMut<'a, K, V> {
1647        self.iter_mut()
1648    }
1649}
1650
1651#[stable(feature = "rust1", since = "1.0.0")]
1652impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1653    type Item = (&'a K, &'a mut V);
1654
1655    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1656        if self.length == 0 {
1657            None
1658        } else {
1659            self.length -= 1;
1660            Some(unsafe { self.range.next_unchecked() })
1661        }
1662    }
1663
1664    fn size_hint(&self) -> (usize, Option<usize>) {
1665        (self.length, Some(self.length))
1666    }
1667
1668    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1669        self.next_back()
1670    }
1671
1672    fn min(mut self) -> Option<(&'a K, &'a mut V)>
1673    where
1674        (&'a K, &'a mut V): Ord,
1675    {
1676        self.next()
1677    }
1678
1679    fn max(mut self) -> Option<(&'a K, &'a mut V)>
1680    where
1681        (&'a K, &'a mut V): Ord,
1682    {
1683        self.next_back()
1684    }
1685}
1686
1687#[stable(feature = "rust1", since = "1.0.0")]
1688impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1689    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1690        if self.length == 0 {
1691            None
1692        } else {
1693            self.length -= 1;
1694            Some(unsafe { self.range.next_back_unchecked() })
1695        }
1696    }
1697}
1698
1699#[stable(feature = "rust1", since = "1.0.0")]
1700impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1701    fn len(&self) -> usize {
1702        self.length
1703    }
1704}
1705
1706#[unstable(feature = "trusted_len", issue = "37572")]
1707unsafe impl<K, V> TrustedLen for IterMut<'_, K, V> {}
1708
1709#[stable(feature = "fused", since = "1.26.0")]
1710impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1711
1712impl<'a, K, V> IterMut<'a, K, V> {
1713    /// Returns an iterator of references over the remaining items.
1714    #[inline]
1715    pub(super) fn iter(&self) -> Iter<'_, K, V> {
1716        Iter { range: self.range.reborrow(), length: self.length }
1717    }
1718}
1719
1720#[stable(feature = "rust1", since = "1.0.0")]
1721impl<K, V, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, A> {
1722    type Item = (K, V);
1723    type IntoIter = IntoIter<K, V, A>;
1724
1725    /// Gets an owning iterator over the entries of the map, sorted by key.
1726    fn into_iter(self) -> IntoIter<K, V, A> {
1727        let mut me = ManuallyDrop::new(self);
1728        if let Some(root) = me.root.take() {
1729            let full_range = root.into_dying().full_range();
1730
1731            IntoIter {
1732                range: full_range,
1733                length: me.length,
1734                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1735            }
1736        } else {
1737            IntoIter {
1738                range: LazyLeafRange::none(),
1739                length: 0,
1740                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1741            }
1742        }
1743    }
1744}
1745
1746#[stable(feature = "btree_drop", since = "1.7.0")]
1747impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
1748    fn drop(&mut self) {
1749        struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
1750
1751        impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
1752            fn drop(&mut self) {
1753                // Continue the same loop we perform below. This only runs when unwinding, so we
1754                // don't have to care about panics this time (they'll abort).
1755                while let Some(kv) = self.0.dying_next() {
1756                    // SAFETY: we consume the dying handle immediately.
1757                    unsafe { kv.drop_key_val() };
1758                }
1759            }
1760        }
1761
1762        while let Some(kv) = self.dying_next() {
1763            let guard = DropGuard(self);
1764            // SAFETY: we don't touch the tree before consuming the dying handle.
1765            unsafe { kv.drop_key_val() };
1766            mem::forget(guard);
1767        }
1768    }
1769}
1770
1771impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
1772    /// Core of a `next` method returning a dying KV handle,
1773    /// invalidated by further calls to this function and some others.
1774    fn dying_next(
1775        &mut self,
1776    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1777        if self.length == 0 {
1778            self.range.deallocating_end(self.alloc.clone());
1779            None
1780        } else {
1781            self.length -= 1;
1782            Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1783        }
1784    }
1785
1786    /// Core of a `next_back` method returning a dying KV handle,
1787    /// invalidated by further calls to this function and some others.
1788    fn dying_next_back(
1789        &mut self,
1790    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1791        if self.length == 0 {
1792            self.range.deallocating_end(self.alloc.clone());
1793            None
1794        } else {
1795            self.length -= 1;
1796            Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1797        }
1798    }
1799}
1800
1801#[stable(feature = "rust1", since = "1.0.0")]
1802impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
1803    type Item = (K, V);
1804
1805    fn next(&mut self) -> Option<(K, V)> {
1806        // SAFETY: we consume the dying handle immediately.
1807        self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1808    }
1809
1810    fn size_hint(&self) -> (usize, Option<usize>) {
1811        (self.length, Some(self.length))
1812    }
1813}
1814
1815#[stable(feature = "rust1", since = "1.0.0")]
1816impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
1817    fn next_back(&mut self) -> Option<(K, V)> {
1818        // SAFETY: we consume the dying handle immediately.
1819        self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1820    }
1821}
1822
1823#[stable(feature = "rust1", since = "1.0.0")]
1824impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
1825    fn len(&self) -> usize {
1826        self.length
1827    }
1828}
1829
1830#[unstable(feature = "trusted_len", issue = "37572")]
1831unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoIter<K, V, A> {}
1832
1833#[stable(feature = "fused", since = "1.26.0")]
1834impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
1835
1836#[stable(feature = "rust1", since = "1.0.0")]
1837impl<'a, K, V> Iterator for Keys<'a, K, V> {
1838    type Item = &'a K;
1839
1840    fn next(&mut self) -> Option<&'a K> {
1841        self.inner.next().map(|(k, _)| k)
1842    }
1843
1844    fn size_hint(&self) -> (usize, Option<usize>) {
1845        self.inner.size_hint()
1846    }
1847
1848    fn last(mut self) -> Option<&'a K> {
1849        self.next_back()
1850    }
1851
1852    fn min(mut self) -> Option<&'a K>
1853    where
1854        &'a K: Ord,
1855    {
1856        self.next()
1857    }
1858
1859    fn max(mut self) -> Option<&'a K>
1860    where
1861        &'a K: Ord,
1862    {
1863        self.next_back()
1864    }
1865}
1866
1867#[stable(feature = "rust1", since = "1.0.0")]
1868impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1869    fn next_back(&mut self) -> Option<&'a K> {
1870        self.inner.next_back().map(|(k, _)| k)
1871    }
1872}
1873
1874#[stable(feature = "rust1", since = "1.0.0")]
1875impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1876    fn len(&self) -> usize {
1877        self.inner.len()
1878    }
1879}
1880
1881#[unstable(feature = "trusted_len", issue = "37572")]
1882unsafe impl<K, V> TrustedLen for Keys<'_, K, V> {}
1883
1884#[stable(feature = "fused", since = "1.26.0")]
1885impl<K, V> FusedIterator for Keys<'_, K, V> {}
1886
1887#[stable(feature = "rust1", since = "1.0.0")]
1888impl<K, V> Clone for Keys<'_, K, V> {
1889    fn clone(&self) -> Self {
1890        Keys { inner: self.inner.clone() }
1891    }
1892}
1893
1894#[stable(feature = "default_iters", since = "1.70.0")]
1895impl<K, V> Default for Keys<'_, K, V> {
1896    /// Creates an empty `btree_map::Keys`.
1897    ///
1898    /// ```
1899    /// # use std::collections::btree_map;
1900    /// let iter: btree_map::Keys<'_, u8, u8> = Default::default();
1901    /// assert_eq!(iter.len(), 0);
1902    /// ```
1903    fn default() -> Self {
1904        Keys { inner: Default::default() }
1905    }
1906}
1907
1908#[stable(feature = "rust1", since = "1.0.0")]
1909impl<'a, K, V> Iterator for Values<'a, K, V> {
1910    type Item = &'a V;
1911
1912    fn next(&mut self) -> Option<&'a V> {
1913        self.inner.next().map(|(_, v)| v)
1914    }
1915
1916    fn size_hint(&self) -> (usize, Option<usize>) {
1917        self.inner.size_hint()
1918    }
1919
1920    fn last(mut self) -> Option<&'a V> {
1921        self.next_back()
1922    }
1923}
1924
1925#[stable(feature = "rust1", since = "1.0.0")]
1926impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1927    fn next_back(&mut self) -> Option<&'a V> {
1928        self.inner.next_back().map(|(_, v)| v)
1929    }
1930}
1931
1932#[stable(feature = "rust1", since = "1.0.0")]
1933impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1934    fn len(&self) -> usize {
1935        self.inner.len()
1936    }
1937}
1938
1939#[unstable(feature = "trusted_len", issue = "37572")]
1940unsafe impl<K, V> TrustedLen for Values<'_, K, V> {}
1941
1942#[stable(feature = "fused", since = "1.26.0")]
1943impl<K, V> FusedIterator for Values<'_, K, V> {}
1944
1945#[stable(feature = "rust1", since = "1.0.0")]
1946impl<K, V> Clone for Values<'_, K, V> {
1947    fn clone(&self) -> Self {
1948        Values { inner: self.inner.clone() }
1949    }
1950}
1951
1952#[stable(feature = "default_iters", since = "1.70.0")]
1953impl<K, V> Default for Values<'_, K, V> {
1954    /// Creates an empty `btree_map::Values`.
1955    ///
1956    /// ```
1957    /// # use std::collections::btree_map;
1958    /// let iter: btree_map::Values<'_, u8, u8> = Default::default();
1959    /// assert_eq!(iter.len(), 0);
1960    /// ```
1961    fn default() -> Self {
1962        Values { inner: Default::default() }
1963    }
1964}
1965
1966/// An iterator produced by calling `extract_if` on BTreeMap.
1967#[stable(feature = "btree_extract_if", since = "1.91.0")]
1968#[must_use = "iterators are lazy and do nothing unless consumed; \
1969    use `retain` or `extract_if().for_each(drop)` to remove and discard elements"]
1970pub struct ExtractIf<
1971    'a,
1972    K,
1973    V,
1974    R,
1975    F,
1976    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
1977> {
1978    pred: F,
1979    inner: ExtractIfInner<'a, K, V, R>,
1980    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1981    alloc: A,
1982}
1983
1984/// Most of the implementation of ExtractIf are generic over the type
1985/// of the predicate, thus also serving for BTreeSet::ExtractIf.
1986pub(super) struct ExtractIfInner<'a, K, V, R> {
1987    /// Reference to the length field in the borrowed map, updated live.
1988    length: &'a mut usize,
1989    /// Buried reference to the root field in the borrowed map.
1990    /// Wrapped in `Option` to allow drop handler to `take` it.
1991    dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1992    /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1993    /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1994    /// or if a panic occurred in the predicate.
1995    cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1996    /// Range over which iteration was requested.  We don't need the left side, but we
1997    /// can't extract the right side without requiring K: Clone.
1998    range: R,
1999}
2000
2001#[stable(feature = "btree_extract_if", since = "1.91.0")]
2002impl<K, V, R, F, A> fmt::Debug for ExtractIf<'_, K, V, R, F, A>
2003where
2004    K: fmt::Debug,
2005    V: fmt::Debug,
2006    A: Allocator + Clone,
2007{
2008    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2009        f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive()
2010    }
2011}
2012
2013#[stable(feature = "btree_extract_if", since = "1.91.0")]
2014impl<K, V, R, F, A: Allocator + Clone> Iterator for ExtractIf<'_, K, V, R, F, A>
2015where
2016    K: PartialOrd,
2017    R: RangeBounds<K>,
2018    F: FnMut(&K, &mut V) -> bool,
2019{
2020    type Item = (K, V);
2021
2022    fn next(&mut self) -> Option<(K, V)> {
2023        self.inner.next(&mut self.pred, self.alloc.clone())
2024    }
2025
2026    fn size_hint(&self) -> (usize, Option<usize>) {
2027        self.inner.size_hint()
2028    }
2029}
2030
2031impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
2032    /// Allow Debug implementations to predict the next element.
2033    pub(super) fn peek(&self) -> Option<(&K, &V)> {
2034        let edge = self.cur_leaf_edge.as_ref()?;
2035        edge.reborrow().next_kv().ok().map(Handle::into_kv)
2036    }
2037
2038    /// Implementation of a typical `ExtractIf::next` method, given the predicate.
2039    pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
2040    where
2041        K: PartialOrd,
2042        R: RangeBounds<K>,
2043        F: FnMut(&K, &mut V) -> bool,
2044    {
2045        while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
2046            let (k, v) = kv.kv_mut();
2047
2048            // On creation, we navigated directly to the left bound, so we need only check the
2049            // right bound here to decide whether to stop.
2050            match self.range.end_bound() {
2051                Bound::Included(ref end) if (*k).le(end) => (),
2052                Bound::Excluded(ref end) if (*k).lt(end) => (),
2053                Bound::Unbounded => (),
2054                _ => return None,
2055            }
2056
2057            if pred(k, v) {
2058                *self.length -= 1;
2059                let (kv, pos) = kv.remove_kv_tracking(
2060                    || {
2061                        // SAFETY: we will touch the root in a way that will not
2062                        // invalidate the position returned.
2063                        let root = unsafe { self.dormant_root.take().unwrap().awaken() };
2064                        root.pop_internal_level(alloc.clone());
2065                        self.dormant_root = Some(DormantMutRef::new(root).1);
2066                    },
2067                    alloc.clone(),
2068                );
2069                self.cur_leaf_edge = Some(pos);
2070                return Some(kv);
2071            }
2072            self.cur_leaf_edge = Some(kv.next_leaf_edge());
2073        }
2074        None
2075    }
2076
2077    /// Implementation of a typical `ExtractIf::size_hint` method.
2078    pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
2079        // In most of the btree iterators, `self.length` is the number of elements
2080        // yet to be visited. Here, it includes elements that were visited and that
2081        // the predicate decided not to drain. Making this upper bound more tight
2082        // during iteration would require an extra field.
2083        (0, Some(*self.length))
2084    }
2085}
2086
2087#[stable(feature = "btree_extract_if", since = "1.91.0")]
2088impl<K, V, R, F> FusedIterator for ExtractIf<'_, K, V, R, F>
2089where
2090    K: PartialOrd,
2091    R: RangeBounds<K>,
2092    F: FnMut(&K, &mut V) -> bool,
2093{
2094}
2095
2096#[stable(feature = "btree_range", since = "1.17.0")]
2097impl<'a, K, V> Iterator for Range<'a, K, V> {
2098    type Item = (&'a K, &'a V);
2099
2100    fn next(&mut self) -> Option<(&'a K, &'a V)> {
2101        self.inner.next_checked()
2102    }
2103
2104    fn last(mut self) -> Option<(&'a K, &'a V)> {
2105        self.next_back()
2106    }
2107
2108    fn min(mut self) -> Option<(&'a K, &'a V)>
2109    where
2110        (&'a K, &'a V): Ord,
2111    {
2112        self.next()
2113    }
2114
2115    fn max(mut self) -> Option<(&'a K, &'a V)>
2116    where
2117        (&'a K, &'a V): Ord,
2118    {
2119        self.next_back()
2120    }
2121}
2122
2123#[stable(feature = "default_iters", since = "1.70.0")]
2124impl<K, V> Default for Range<'_, K, V> {
2125    /// Creates an empty `btree_map::Range`.
2126    ///
2127    /// ```
2128    /// # use std::collections::btree_map;
2129    /// let iter: btree_map::Range<'_, u8, u8> = Default::default();
2130    /// assert_eq!(iter.count(), 0);
2131    /// ```
2132    fn default() -> Self {
2133        Range { inner: Default::default() }
2134    }
2135}
2136
2137#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2138impl<K, V> Default for RangeMut<'_, K, V> {
2139    /// Creates an empty `btree_map::RangeMut`.
2140    ///
2141    /// ```
2142    /// # use std::collections::btree_map;
2143    /// let iter: btree_map::RangeMut<'_, u8, u8> = Default::default();
2144    /// assert_eq!(iter.count(), 0);
2145    /// ```
2146    fn default() -> Self {
2147        RangeMut { inner: Default::default(), _marker: PhantomData }
2148    }
2149}
2150
2151#[stable(feature = "map_values_mut", since = "1.10.0")]
2152impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2153    type Item = &'a mut V;
2154
2155    fn next(&mut self) -> Option<&'a mut V> {
2156        self.inner.next().map(|(_, v)| v)
2157    }
2158
2159    fn size_hint(&self) -> (usize, Option<usize>) {
2160        self.inner.size_hint()
2161    }
2162
2163    fn last(mut self) -> Option<&'a mut V> {
2164        self.next_back()
2165    }
2166}
2167
2168#[stable(feature = "map_values_mut", since = "1.10.0")]
2169impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2170    fn next_back(&mut self) -> Option<&'a mut V> {
2171        self.inner.next_back().map(|(_, v)| v)
2172    }
2173}
2174
2175#[stable(feature = "map_values_mut", since = "1.10.0")]
2176impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2177    fn len(&self) -> usize {
2178        self.inner.len()
2179    }
2180}
2181
2182#[unstable(feature = "trusted_len", issue = "37572")]
2183unsafe impl<K, V> TrustedLen for ValuesMut<'_, K, V> {}
2184
2185#[stable(feature = "fused", since = "1.26.0")]
2186impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2187
2188#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2189impl<K, V> Default for ValuesMut<'_, K, V> {
2190    /// Creates an empty `btree_map::ValuesMut`.
2191    ///
2192    /// ```
2193    /// # use std::collections::btree_map;
2194    /// let iter: btree_map::ValuesMut<'_, u8, u8> = Default::default();
2195    /// assert_eq!(iter.count(), 0);
2196    /// ```
2197    fn default() -> Self {
2198        ValuesMut { inner: Default::default() }
2199    }
2200}
2201
2202#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2203impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
2204    type Item = K;
2205
2206    fn next(&mut self) -> Option<K> {
2207        self.inner.next().map(|(k, _)| k)
2208    }
2209
2210    fn size_hint(&self) -> (usize, Option<usize>) {
2211        self.inner.size_hint()
2212    }
2213
2214    fn last(mut self) -> Option<K> {
2215        self.next_back()
2216    }
2217
2218    fn min(mut self) -> Option<K>
2219    where
2220        K: Ord,
2221    {
2222        self.next()
2223    }
2224
2225    fn max(mut self) -> Option<K>
2226    where
2227        K: Ord,
2228    {
2229        self.next_back()
2230    }
2231}
2232
2233#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2234impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
2235    fn next_back(&mut self) -> Option<K> {
2236        self.inner.next_back().map(|(k, _)| k)
2237    }
2238}
2239
2240#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2241impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
2242    fn len(&self) -> usize {
2243        self.inner.len()
2244    }
2245}
2246
2247#[unstable(feature = "trusted_len", issue = "37572")]
2248unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoKeys<K, V, A> {}
2249
2250#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2251impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
2252
2253#[stable(feature = "default_iters", since = "1.70.0")]
2254impl<K, V, A> Default for IntoKeys<K, V, A>
2255where
2256    A: Allocator + Default + Clone,
2257{
2258    /// Creates an empty `btree_map::IntoKeys`.
2259    ///
2260    /// ```
2261    /// # use std::collections::btree_map;
2262    /// let iter: btree_map::IntoKeys<u8, u8> = Default::default();
2263    /// assert_eq!(iter.len(), 0);
2264    /// ```
2265    fn default() -> Self {
2266        IntoKeys { inner: Default::default() }
2267    }
2268}
2269
2270#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2271impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
2272    type Item = V;
2273
2274    fn next(&mut self) -> Option<V> {
2275        self.inner.next().map(|(_, v)| v)
2276    }
2277
2278    fn size_hint(&self) -> (usize, Option<usize>) {
2279        self.inner.size_hint()
2280    }
2281
2282    fn last(mut self) -> Option<V> {
2283        self.next_back()
2284    }
2285}
2286
2287#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2288impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
2289    fn next_back(&mut self) -> Option<V> {
2290        self.inner.next_back().map(|(_, v)| v)
2291    }
2292}
2293
2294#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2295impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
2296    fn len(&self) -> usize {
2297        self.inner.len()
2298    }
2299}
2300
2301#[unstable(feature = "trusted_len", issue = "37572")]
2302unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoValues<K, V, A> {}
2303
2304#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2305impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
2306
2307#[stable(feature = "default_iters", since = "1.70.0")]
2308impl<K, V, A> Default for IntoValues<K, V, A>
2309where
2310    A: Allocator + Default + Clone,
2311{
2312    /// Creates an empty `btree_map::IntoValues`.
2313    ///
2314    /// ```
2315    /// # use std::collections::btree_map;
2316    /// let iter: btree_map::IntoValues<u8, u8> = Default::default();
2317    /// assert_eq!(iter.len(), 0);
2318    /// ```
2319    fn default() -> Self {
2320        IntoValues { inner: Default::default() }
2321    }
2322}
2323
2324#[stable(feature = "btree_range", since = "1.17.0")]
2325impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2326    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2327        self.inner.next_back_checked()
2328    }
2329}
2330
2331#[stable(feature = "fused", since = "1.26.0")]
2332impl<K, V> FusedIterator for Range<'_, K, V> {}
2333
2334#[stable(feature = "btree_range", since = "1.17.0")]
2335impl<K, V> Clone for Range<'_, K, V> {
2336    fn clone(&self) -> Self {
2337        Range { inner: self.inner.clone() }
2338    }
2339}
2340
2341#[stable(feature = "btree_range", since = "1.17.0")]
2342impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2343    type Item = (&'a K, &'a mut V);
2344
2345    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2346        self.inner.next_checked()
2347    }
2348
2349    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2350        self.next_back()
2351    }
2352
2353    fn min(mut self) -> Option<(&'a K, &'a mut V)>
2354    where
2355        (&'a K, &'a mut V): Ord,
2356    {
2357        self.next()
2358    }
2359
2360    fn max(mut self) -> Option<(&'a K, &'a mut V)>
2361    where
2362        (&'a K, &'a mut V): Ord,
2363    {
2364        self.next_back()
2365    }
2366}
2367
2368#[stable(feature = "btree_range", since = "1.17.0")]
2369impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2370    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2371        self.inner.next_back_checked()
2372    }
2373}
2374
2375#[stable(feature = "fused", since = "1.26.0")]
2376impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2377
2378#[stable(feature = "rust1", since = "1.0.0")]
2379impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2380    /// Constructs a `BTreeMap<K, V>` from an iterator of key-value pairs.
2381    ///
2382    /// If the iterator produces any pairs with equal keys,
2383    /// all but one of the corresponding values will be dropped.
2384    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2385        let mut inputs: Vec<_> = iter.into_iter().collect();
2386
2387        if inputs.is_empty() {
2388            return BTreeMap::new();
2389        }
2390
2391        // use stable sort to preserve the insertion order.
2392        inputs.sort_by(|a, b| a.0.cmp(&b.0));
2393        BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2394    }
2395}
2396
2397#[stable(feature = "rust1", since = "1.0.0")]
2398impl<K: Ord, V, A: Allocator + Clone> Extend<(K, V)> for BTreeMap<K, V, A> {
2399    #[inline]
2400    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2401        iter.into_iter().for_each(move |(k, v)| {
2402            self.insert(k, v);
2403        });
2404    }
2405
2406    #[inline]
2407    fn extend_one(&mut self, (k, v): (K, V)) {
2408        self.insert(k, v);
2409    }
2410}
2411
2412#[stable(feature = "extend_ref", since = "1.2.0")]
2413impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)>
2414    for BTreeMap<K, V, A>
2415{
2416    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2417        self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2418    }
2419
2420    #[inline]
2421    fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2422        self.insert(k, v);
2423    }
2424}
2425
2426#[stable(feature = "rust1", since = "1.0.0")]
2427impl<K: Hash, V: Hash, A: Allocator + Clone> Hash for BTreeMap<K, V, A> {
2428    fn hash<H: Hasher>(&self, state: &mut H) {
2429        state.write_length_prefix(self.len());
2430        for elt in self {
2431            elt.hash(state);
2432        }
2433    }
2434}
2435
2436#[stable(feature = "rust1", since = "1.0.0")]
2437impl<K, V> Default for BTreeMap<K, V> {
2438    /// Creates an empty `BTreeMap`.
2439    fn default() -> BTreeMap<K, V> {
2440        BTreeMap::new()
2441    }
2442}
2443
2444#[stable(feature = "rust1", since = "1.0.0")]
2445impl<K: PartialEq, V: PartialEq, A: Allocator + Clone> PartialEq for BTreeMap<K, V, A> {
2446    fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2447        self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2448    }
2449}
2450
2451#[stable(feature = "rust1", since = "1.0.0")]
2452impl<K: Eq, V: Eq, A: Allocator + Clone> Eq for BTreeMap<K, V, A> {}
2453
2454#[stable(feature = "rust1", since = "1.0.0")]
2455impl<K: PartialOrd, V: PartialOrd, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, A> {
2456    #[inline]
2457    fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2458        self.iter().partial_cmp(other.iter())
2459    }
2460}
2461
2462#[stable(feature = "rust1", since = "1.0.0")]
2463impl<K: Ord, V: Ord, A: Allocator + Clone> Ord for BTreeMap<K, V, A> {
2464    #[inline]
2465    fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2466        self.iter().cmp(other.iter())
2467    }
2468}
2469
2470#[stable(feature = "rust1", since = "1.0.0")]
2471impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for BTreeMap<K, V, A> {
2472    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2473        f.debug_map().entries(self.iter()).finish()
2474    }
2475}
2476
2477#[stable(feature = "rust1", since = "1.0.0")]
2478impl<K, Q: ?Sized, V, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, A>
2479where
2480    K: Borrow<Q> + Ord,
2481    Q: Ord,
2482{
2483    type Output = V;
2484
2485    /// Returns a reference to the value corresponding to the supplied key.
2486    ///
2487    /// # Panics
2488    ///
2489    /// Panics if the key is not present in the `BTreeMap`.
2490    #[inline]
2491    fn index(&self, key: &Q) -> &V {
2492        self.get(key).expect("no entry found for key")
2493    }
2494}
2495
2496#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2497impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2498    /// Converts a `[(K, V); N]` into a `BTreeMap<K, V>`.
2499    ///
2500    /// If any entries in the array have equal keys,
2501    /// all but one of the corresponding values will be dropped.
2502    ///
2503    /// ```
2504    /// use std::collections::BTreeMap;
2505    ///
2506    /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2507    /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2508    /// assert_eq!(map1, map2);
2509    /// ```
2510    fn from(mut arr: [(K, V); N]) -> Self {
2511        if N == 0 {
2512            return BTreeMap::new();
2513        }
2514
2515        // use stable sort to preserve the insertion order.
2516        arr.sort_by(|a, b| a.0.cmp(&b.0));
2517        BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2518    }
2519}
2520
2521impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
2522    /// Gets an iterator over the entries of the map, sorted by key.
2523    ///
2524    /// # Examples
2525    ///
2526    /// ```
2527    /// use std::collections::BTreeMap;
2528    ///
2529    /// let mut map = BTreeMap::new();
2530    /// map.insert(3, "c");
2531    /// map.insert(2, "b");
2532    /// map.insert(1, "a");
2533    ///
2534    /// for (key, value) in map.iter() {
2535    ///     println!("{key}: {value}");
2536    /// }
2537    ///
2538    /// let (first_key, first_value) = map.iter().next().unwrap();
2539    /// assert_eq!((*first_key, *first_value), (1, "a"));
2540    /// ```
2541    #[stable(feature = "rust1", since = "1.0.0")]
2542    pub fn iter(&self) -> Iter<'_, K, V> {
2543        if let Some(root) = &self.root {
2544            let full_range = root.reborrow().full_range();
2545
2546            Iter { range: full_range, length: self.length }
2547        } else {
2548            Iter { range: LazyLeafRange::none(), length: 0 }
2549        }
2550    }
2551
2552    /// Gets a mutable iterator over the entries of the map, sorted by key.
2553    ///
2554    /// # Examples
2555    ///
2556    /// ```
2557    /// use std::collections::BTreeMap;
2558    ///
2559    /// let mut map = BTreeMap::from([
2560    ///    ("a", 1),
2561    ///    ("b", 2),
2562    ///    ("c", 3),
2563    /// ]);
2564    ///
2565    /// // add 10 to the value if the key isn't "a"
2566    /// for (key, value) in map.iter_mut() {
2567    ///     if key != &"a" {
2568    ///         *value += 10;
2569    ///     }
2570    /// }
2571    /// ```
2572    #[stable(feature = "rust1", since = "1.0.0")]
2573    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2574        if let Some(root) = &mut self.root {
2575            let full_range = root.borrow_valmut().full_range();
2576
2577            IterMut { range: full_range, length: self.length, _marker: PhantomData }
2578        } else {
2579            IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2580        }
2581    }
2582
2583    /// Gets an iterator over the keys of the map, in sorted order.
2584    ///
2585    /// # Examples
2586    ///
2587    /// ```
2588    /// use std::collections::BTreeMap;
2589    ///
2590    /// let mut a = BTreeMap::new();
2591    /// a.insert(2, "b");
2592    /// a.insert(1, "a");
2593    ///
2594    /// let keys: Vec<_> = a.keys().cloned().collect();
2595    /// assert_eq!(keys, [1, 2]);
2596    /// ```
2597    #[stable(feature = "rust1", since = "1.0.0")]
2598    pub fn keys(&self) -> Keys<'_, K, V> {
2599        Keys { inner: self.iter() }
2600    }
2601
2602    /// Gets an iterator over the values of the map, in order by key.
2603    ///
2604    /// # Examples
2605    ///
2606    /// ```
2607    /// use std::collections::BTreeMap;
2608    ///
2609    /// let mut a = BTreeMap::new();
2610    /// a.insert(1, "hello");
2611    /// a.insert(2, "goodbye");
2612    ///
2613    /// let values: Vec<&str> = a.values().cloned().collect();
2614    /// assert_eq!(values, ["hello", "goodbye"]);
2615    /// ```
2616    #[stable(feature = "rust1", since = "1.0.0")]
2617    pub fn values(&self) -> Values<'_, K, V> {
2618        Values { inner: self.iter() }
2619    }
2620
2621    /// Gets a mutable iterator over the values of the map, in order by key.
2622    ///
2623    /// # Examples
2624    ///
2625    /// ```
2626    /// use std::collections::BTreeMap;
2627    ///
2628    /// let mut a = BTreeMap::new();
2629    /// a.insert(1, String::from("hello"));
2630    /// a.insert(2, String::from("goodbye"));
2631    ///
2632    /// for value in a.values_mut() {
2633    ///     value.push_str("!");
2634    /// }
2635    ///
2636    /// let values: Vec<String> = a.values().cloned().collect();
2637    /// assert_eq!(values, [String::from("hello!"),
2638    ///                     String::from("goodbye!")]);
2639    /// ```
2640    #[stable(feature = "map_values_mut", since = "1.10.0")]
2641    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2642        ValuesMut { inner: self.iter_mut() }
2643    }
2644
2645    /// Returns the number of elements in the map.
2646    ///
2647    /// # Examples
2648    ///
2649    /// ```
2650    /// use std::collections::BTreeMap;
2651    ///
2652    /// let mut a = BTreeMap::new();
2653    /// assert_eq!(a.len(), 0);
2654    /// a.insert(1, "a");
2655    /// assert_eq!(a.len(), 1);
2656    /// ```
2657    #[must_use]
2658    #[stable(feature = "rust1", since = "1.0.0")]
2659    #[rustc_const_unstable(
2660        feature = "const_btree_len",
2661        issue = "71835",
2662        implied_by = "const_btree_new"
2663    )]
2664    #[rustc_confusables("length", "size")]
2665    pub const fn len(&self) -> usize {
2666        self.length
2667    }
2668
2669    /// Returns `true` if the map contains no elements.
2670    ///
2671    /// # Examples
2672    ///
2673    /// ```
2674    /// use std::collections::BTreeMap;
2675    ///
2676    /// let mut a = BTreeMap::new();
2677    /// assert!(a.is_empty());
2678    /// a.insert(1, "a");
2679    /// assert!(!a.is_empty());
2680    /// ```
2681    #[must_use]
2682    #[stable(feature = "rust1", since = "1.0.0")]
2683    #[rustc_const_unstable(
2684        feature = "const_btree_len",
2685        issue = "71835",
2686        implied_by = "const_btree_new"
2687    )]
2688    pub const fn is_empty(&self) -> bool {
2689        self.len() == 0
2690    }
2691
2692    /// Returns a [`Cursor`] pointing at the gap before the smallest key
2693    /// greater than the given bound.
2694    ///
2695    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2696    /// gap before the smallest key greater than or equal to `x`.
2697    ///
2698    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2699    /// gap before the smallest key greater than `x`.
2700    ///
2701    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2702    /// gap before the smallest key in the map.
2703    ///
2704    /// # Examples
2705    ///
2706    /// ```
2707    /// #![feature(btree_cursors)]
2708    ///
2709    /// use std::collections::BTreeMap;
2710    /// use std::ops::Bound;
2711    ///
2712    /// let map = BTreeMap::from([
2713    ///     (1, "a"),
2714    ///     (2, "b"),
2715    ///     (3, "c"),
2716    ///     (4, "d"),
2717    /// ]);
2718    ///
2719    /// let cursor = map.lower_bound(Bound::Included(&2));
2720    /// assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
2721    /// assert_eq!(cursor.peek_next(), Some((&2, &"b")));
2722    ///
2723    /// let cursor = map.lower_bound(Bound::Excluded(&2));
2724    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2725    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2726    ///
2727    /// let cursor = map.lower_bound(Bound::Unbounded);
2728    /// assert_eq!(cursor.peek_prev(), None);
2729    /// assert_eq!(cursor.peek_next(), Some((&1, &"a")));
2730    /// ```
2731    #[unstable(feature = "btree_cursors", issue = "107540")]
2732    pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2733    where
2734        K: Borrow<Q> + Ord,
2735        Q: Ord,
2736    {
2737        let root_node = match self.root.as_ref() {
2738            None => return Cursor { current: None, root: None },
2739            Some(root) => root.reborrow(),
2740        };
2741        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2742        Cursor { current: Some(edge), root: self.root.as_ref() }
2743    }
2744
2745    /// Returns a [`CursorMut`] pointing at the gap before the smallest key
2746    /// greater than the given bound.
2747    ///
2748    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2749    /// gap before the smallest key greater than or equal to `x`.
2750    ///
2751    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2752    /// gap before the smallest key greater than `x`.
2753    ///
2754    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2755    /// gap before the smallest key in the map.
2756    ///
2757    /// # Examples
2758    ///
2759    /// ```
2760    /// #![feature(btree_cursors)]
2761    ///
2762    /// use std::collections::BTreeMap;
2763    /// use std::ops::Bound;
2764    ///
2765    /// let mut map = BTreeMap::from([
2766    ///     (1, "a"),
2767    ///     (2, "b"),
2768    ///     (3, "c"),
2769    ///     (4, "d"),
2770    /// ]);
2771    ///
2772    /// let mut cursor = map.lower_bound_mut(Bound::Included(&2));
2773    /// assert_eq!(cursor.peek_prev(), Some((&1, &mut "a")));
2774    /// assert_eq!(cursor.peek_next(), Some((&2, &mut "b")));
2775    ///
2776    /// let mut cursor = map.lower_bound_mut(Bound::Excluded(&2));
2777    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2778    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2779    ///
2780    /// let mut cursor = map.lower_bound_mut(Bound::Unbounded);
2781    /// assert_eq!(cursor.peek_prev(), None);
2782    /// assert_eq!(cursor.peek_next(), Some((&1, &mut "a")));
2783    /// ```
2784    #[unstable(feature = "btree_cursors", issue = "107540")]
2785    pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2786    where
2787        K: Borrow<Q> + Ord,
2788        Q: Ord,
2789    {
2790        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2791        let root_node = match root.as_mut() {
2792            None => {
2793                return CursorMut {
2794                    inner: CursorMutKey {
2795                        current: None,
2796                        root: dormant_root,
2797                        length: &mut self.length,
2798                        alloc: &mut *self.alloc,
2799                    },
2800                };
2801            }
2802            Some(root) => root.borrow_mut(),
2803        };
2804        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2805        CursorMut {
2806            inner: CursorMutKey {
2807                current: Some(edge),
2808                root: dormant_root,
2809                length: &mut self.length,
2810                alloc: &mut *self.alloc,
2811            },
2812        }
2813    }
2814
2815    /// Returns a [`Cursor`] pointing at the gap after the greatest key
2816    /// smaller than the given bound.
2817    ///
2818    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2819    /// gap after the greatest key smaller than or equal to `x`.
2820    ///
2821    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2822    /// gap after the greatest key smaller than `x`.
2823    ///
2824    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2825    /// gap after the greatest key in the map.
2826    ///
2827    /// # Examples
2828    ///
2829    /// ```
2830    /// #![feature(btree_cursors)]
2831    ///
2832    /// use std::collections::BTreeMap;
2833    /// use std::ops::Bound;
2834    ///
2835    /// let map = BTreeMap::from([
2836    ///     (1, "a"),
2837    ///     (2, "b"),
2838    ///     (3, "c"),
2839    ///     (4, "d"),
2840    /// ]);
2841    ///
2842    /// let cursor = map.upper_bound(Bound::Included(&3));
2843    /// assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
2844    /// assert_eq!(cursor.peek_next(), Some((&4, &"d")));
2845    ///
2846    /// let cursor = map.upper_bound(Bound::Excluded(&3));
2847    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2848    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2849    ///
2850    /// let cursor = map.upper_bound(Bound::Unbounded);
2851    /// assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
2852    /// assert_eq!(cursor.peek_next(), None);
2853    /// ```
2854    #[unstable(feature = "btree_cursors", issue = "107540")]
2855    pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2856    where
2857        K: Borrow<Q> + Ord,
2858        Q: Ord,
2859    {
2860        let root_node = match self.root.as_ref() {
2861            None => return Cursor { current: None, root: None },
2862            Some(root) => root.reborrow(),
2863        };
2864        let edge = root_node.upper_bound(SearchBound::from_range(bound));
2865        Cursor { current: Some(edge), root: self.root.as_ref() }
2866    }
2867
2868    /// Returns a [`CursorMut`] pointing at the gap after the greatest key
2869    /// smaller than the given bound.
2870    ///
2871    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2872    /// gap after the greatest key smaller than or equal to `x`.
2873    ///
2874    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2875    /// gap after the greatest key smaller than `x`.
2876    ///
2877    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2878    /// gap after the greatest key in the map.
2879    ///
2880    /// # Examples
2881    ///
2882    /// ```
2883    /// #![feature(btree_cursors)]
2884    ///
2885    /// use std::collections::BTreeMap;
2886    /// use std::ops::Bound;
2887    ///
2888    /// let mut map = BTreeMap::from([
2889    ///     (1, "a"),
2890    ///     (2, "b"),
2891    ///     (3, "c"),
2892    ///     (4, "d"),
2893    /// ]);
2894    ///
2895    /// let mut cursor = map.upper_bound_mut(Bound::Included(&3));
2896    /// assert_eq!(cursor.peek_prev(), Some((&3, &mut "c")));
2897    /// assert_eq!(cursor.peek_next(), Some((&4, &mut "d")));
2898    ///
2899    /// let mut cursor = map.upper_bound_mut(Bound::Excluded(&3));
2900    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2901    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2902    ///
2903    /// let mut cursor = map.upper_bound_mut(Bound::Unbounded);
2904    /// assert_eq!(cursor.peek_prev(), Some((&4, &mut "d")));
2905    /// assert_eq!(cursor.peek_next(), None);
2906    /// ```
2907    #[unstable(feature = "btree_cursors", issue = "107540")]
2908    pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2909    where
2910        K: Borrow<Q> + Ord,
2911        Q: Ord,
2912    {
2913        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2914        let root_node = match root.as_mut() {
2915            None => {
2916                return CursorMut {
2917                    inner: CursorMutKey {
2918                        current: None,
2919                        root: dormant_root,
2920                        length: &mut self.length,
2921                        alloc: &mut *self.alloc,
2922                    },
2923                };
2924            }
2925            Some(root) => root.borrow_mut(),
2926        };
2927        let edge = root_node.upper_bound(SearchBound::from_range(bound));
2928        CursorMut {
2929            inner: CursorMutKey {
2930                current: Some(edge),
2931                root: dormant_root,
2932                length: &mut self.length,
2933                alloc: &mut *self.alloc,
2934            },
2935        }
2936    }
2937}
2938
2939/// A cursor over a `BTreeMap`.
2940///
2941/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
2942///
2943/// Cursors always point to a gap between two elements in the map, and can
2944/// operate on the two immediately adjacent elements.
2945///
2946/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
2947#[unstable(feature = "btree_cursors", issue = "107540")]
2948pub struct Cursor<'a, K: 'a, V: 'a> {
2949    // If current is None then it means the tree has not been allocated yet.
2950    current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2951    root: Option<&'a node::Root<K, V>>,
2952}
2953
2954#[unstable(feature = "btree_cursors", issue = "107540")]
2955impl<K, V> Clone for Cursor<'_, K, V> {
2956    fn clone(&self) -> Self {
2957        let Cursor { current, root } = *self;
2958        Cursor { current, root }
2959    }
2960}
2961
2962#[unstable(feature = "btree_cursors", issue = "107540")]
2963impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
2964    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2965        f.write_str("Cursor")
2966    }
2967}
2968
2969/// A cursor over a `BTreeMap` with editing operations.
2970///
2971/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2972/// safely mutate the map during iteration. This is because the lifetime of its yielded
2973/// references is tied to its own lifetime, instead of just the underlying map. This means
2974/// cursors cannot yield multiple elements at once.
2975///
2976/// Cursors always point to a gap between two elements in the map, and can
2977/// operate on the two immediately adjacent elements.
2978///
2979/// A `CursorMut` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
2980/// methods.
2981#[unstable(feature = "btree_cursors", issue = "107540")]
2982pub struct CursorMut<
2983    'a,
2984    K: 'a,
2985    V: 'a,
2986    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
2987> {
2988    inner: CursorMutKey<'a, K, V, A>,
2989}
2990
2991#[unstable(feature = "btree_cursors", issue = "107540")]
2992impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
2993    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2994        f.write_str("CursorMut")
2995    }
2996}
2997
2998/// A cursor over a `BTreeMap` with editing operations, and which allows
2999/// mutating the key of elements.
3000///
3001/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3002/// safely mutate the map during iteration. This is because the lifetime of its yielded
3003/// references is tied to its own lifetime, instead of just the underlying map. This means
3004/// cursors cannot yield multiple elements at once.
3005///
3006/// Cursors always point to a gap between two elements in the map, and can
3007/// operate on the two immediately adjacent elements.
3008///
3009/// A `CursorMutKey` is created from a [`CursorMut`] with the
3010/// [`CursorMut::with_mutable_key`] method.
3011///
3012/// # Safety
3013///
3014/// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3015/// invariants are maintained. Specifically:
3016///
3017/// * The key of the newly inserted element must be unique in the tree.
3018/// * All keys in the tree must remain in sorted order.
3019#[unstable(feature = "btree_cursors", issue = "107540")]
3020pub struct CursorMutKey<
3021    'a,
3022    K: 'a,
3023    V: 'a,
3024    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3025> {
3026    // If current is None then it means the tree has not been allocated yet.
3027    current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3028    root: DormantMutRef<'a, Option<node::Root<K, V>>>,
3029    length: &'a mut usize,
3030    alloc: &'a mut A,
3031}
3032
3033#[unstable(feature = "btree_cursors", issue = "107540")]
3034impl<K: Debug, V: Debug, A> Debug for CursorMutKey<'_, K, V, A> {
3035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3036        f.write_str("CursorMutKey")
3037    }
3038}
3039
3040impl<'a, K, V> Cursor<'a, K, V> {
3041    /// Advances the cursor to the next gap, returning the key and value of the
3042    /// element that it moved over.
3043    ///
3044    /// If the cursor is already at the end of the map then `None` is returned
3045    /// and the cursor is not moved.
3046    #[unstable(feature = "btree_cursors", issue = "107540")]
3047    pub fn next(&mut self) -> Option<(&'a K, &'a V)> {
3048        let current = self.current.take()?;
3049        match current.next_kv() {
3050            Ok(kv) => {
3051                let result = kv.into_kv();
3052                self.current = Some(kv.next_leaf_edge());
3053                Some(result)
3054            }
3055            Err(root) => {
3056                self.current = Some(root.last_leaf_edge());
3057                None
3058            }
3059        }
3060    }
3061
3062    /// Advances the cursor to the previous gap, returning the key and value of
3063    /// the element that it moved over.
3064    ///
3065    /// If the cursor is already at the start of the map then `None` is returned
3066    /// and the cursor is not moved.
3067    #[unstable(feature = "btree_cursors", issue = "107540")]
3068    pub fn prev(&mut self) -> Option<(&'a K, &'a V)> {
3069        let current = self.current.take()?;
3070        match current.next_back_kv() {
3071            Ok(kv) => {
3072                let result = kv.into_kv();
3073                self.current = Some(kv.next_back_leaf_edge());
3074                Some(result)
3075            }
3076            Err(root) => {
3077                self.current = Some(root.first_leaf_edge());
3078                None
3079            }
3080        }
3081    }
3082
3083    /// Returns a reference to the key and value of the next element without
3084    /// moving the cursor.
3085    ///
3086    /// If the cursor is at the end of the map then `None` is returned.
3087    #[unstable(feature = "btree_cursors", issue = "107540")]
3088    pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3089        self.clone().next()
3090    }
3091
3092    /// Returns a reference to the key and value of the previous element
3093    /// without moving the cursor.
3094    ///
3095    /// If the cursor is at the start of the map then `None` is returned.
3096    #[unstable(feature = "btree_cursors", issue = "107540")]
3097    pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3098        self.clone().prev()
3099    }
3100}
3101
3102impl<'a, K, V, A> CursorMut<'a, K, V, A> {
3103    /// Advances the cursor to the next gap, returning the key and value of the
3104    /// element that it moved over.
3105    ///
3106    /// If the cursor is already at the end of the map then `None` is returned
3107    /// and the cursor is not moved.
3108    #[unstable(feature = "btree_cursors", issue = "107540")]
3109    pub fn next(&mut self) -> Option<(&K, &mut V)> {
3110        let (k, v) = self.inner.next()?;
3111        Some((&*k, v))
3112    }
3113
3114    /// Advances the cursor to the previous gap, returning the key and value of
3115    /// the element that it moved over.
3116    ///
3117    /// If the cursor is already at the start of the map then `None` is returned
3118    /// and the cursor is not moved.
3119    #[unstable(feature = "btree_cursors", issue = "107540")]
3120    pub fn prev(&mut self) -> Option<(&K, &mut V)> {
3121        let (k, v) = self.inner.prev()?;
3122        Some((&*k, v))
3123    }
3124
3125    /// Returns a reference to the key and value of the next element without
3126    /// moving the cursor.
3127    ///
3128    /// If the cursor is at the end of the map then `None` is returned.
3129    #[unstable(feature = "btree_cursors", issue = "107540")]
3130    pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
3131        let (k, v) = self.inner.peek_next()?;
3132        Some((&*k, v))
3133    }
3134
3135    /// Returns a reference to the key and value of the previous element
3136    /// without moving the cursor.
3137    ///
3138    /// If the cursor is at the start of the map then `None` is returned.
3139    #[unstable(feature = "btree_cursors", issue = "107540")]
3140    pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
3141        let (k, v) = self.inner.peek_prev()?;
3142        Some((&*k, v))
3143    }
3144
3145    /// Returns a read-only cursor pointing to the same location as the
3146    /// `CursorMut`.
3147    ///
3148    /// The lifetime of the returned `Cursor` is bound to that of the
3149    /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
3150    /// `CursorMut` is frozen for the lifetime of the `Cursor`.
3151    #[unstable(feature = "btree_cursors", issue = "107540")]
3152    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3153        self.inner.as_cursor()
3154    }
3155
3156    /// Converts the cursor into a [`CursorMutKey`], which allows mutating
3157    /// the key of elements in the tree.
3158    ///
3159    /// # Safety
3160    ///
3161    /// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3162    /// invariants are maintained. Specifically:
3163    ///
3164    /// * The key of the newly inserted element must be unique in the tree.
3165    /// * All keys in the tree must remain in sorted order.
3166    #[unstable(feature = "btree_cursors", issue = "107540")]
3167    pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
3168        self.inner
3169    }
3170}
3171
3172impl<'a, K, V, A> CursorMutKey<'a, K, V, A> {
3173    /// Advances the cursor to the next gap, returning the key and value of the
3174    /// element that it moved over.
3175    ///
3176    /// If the cursor is already at the end of the map then `None` is returned
3177    /// and the cursor is not moved.
3178    #[unstable(feature = "btree_cursors", issue = "107540")]
3179    pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
3180        let current = self.current.take()?;
3181        match current.next_kv() {
3182            Ok(mut kv) => {
3183                // SAFETY: The key/value pointers remain valid even after the
3184                // cursor is moved forward. The lifetimes then prevent any
3185                // further access to the cursor.
3186                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3187                let (k, v) = (k as *mut _, v as *mut _);
3188                self.current = Some(kv.next_leaf_edge());
3189                Some(unsafe { (&mut *k, &mut *v) })
3190            }
3191            Err(root) => {
3192                self.current = Some(root.last_leaf_edge());
3193                None
3194            }
3195        }
3196    }
3197
3198    /// Advances the cursor to the previous gap, returning the key and value of
3199    /// the element that it moved over.
3200    ///
3201    /// If the cursor is already at the start of the map then `None` is returned
3202    /// and the cursor is not moved.
3203    #[unstable(feature = "btree_cursors", issue = "107540")]
3204    pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
3205        let current = self.current.take()?;
3206        match current.next_back_kv() {
3207            Ok(mut kv) => {
3208                // SAFETY: The key/value pointers remain valid even after the
3209                // cursor is moved forward. The lifetimes then prevent any
3210                // further access to the cursor.
3211                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3212                let (k, v) = (k as *mut _, v as *mut _);
3213                self.current = Some(kv.next_back_leaf_edge());
3214                Some(unsafe { (&mut *k, &mut *v) })
3215            }
3216            Err(root) => {
3217                self.current = Some(root.first_leaf_edge());
3218                None
3219            }
3220        }
3221    }
3222
3223    /// Returns a reference to the key and value of the next element without
3224    /// moving the cursor.
3225    ///
3226    /// If the cursor is at the end of the map then `None` is returned.
3227    #[unstable(feature = "btree_cursors", issue = "107540")]
3228    pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> {
3229        let current = self.current.as_mut()?;
3230        // SAFETY: We're not using this to mutate the tree.
3231        let kv = unsafe { current.reborrow_mut() }.next_kv().ok()?.into_kv_mut();
3232        Some(kv)
3233    }
3234
3235    /// Returns a reference to the key and value of the previous element
3236    /// without moving the cursor.
3237    ///
3238    /// If the cursor is at the start of the map then `None` is returned.
3239    #[unstable(feature = "btree_cursors", issue = "107540")]
3240    pub fn peek_prev(&mut self) -> Option<(&mut K, &mut V)> {
3241        let current = self.current.as_mut()?;
3242        // SAFETY: We're not using this to mutate the tree.
3243        let kv = unsafe { current.reborrow_mut() }.next_back_kv().ok()?.into_kv_mut();
3244        Some(kv)
3245    }
3246
3247    /// Returns a read-only cursor pointing to the same location as the
3248    /// `CursorMutKey`.
3249    ///
3250    /// The lifetime of the returned `Cursor` is bound to that of the
3251    /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
3252    /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
3253    #[unstable(feature = "btree_cursors", issue = "107540")]
3254    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3255        Cursor {
3256            // SAFETY: The tree is immutable while the cursor exists.
3257            root: unsafe { self.root.reborrow_shared().as_ref() },
3258            current: self.current.as_ref().map(|current| current.reborrow()),
3259        }
3260    }
3261}
3262
3263// Now the tree editing operations
3264impl<'a, K: Ord, V, A: Allocator + Clone> CursorMutKey<'a, K, V, A> {
3265    /// Inserts a new key-value pair into the map in the gap that the
3266    /// cursor is currently pointing to.
3267    ///
3268    /// After the insertion the cursor will be pointing at the gap before the
3269    /// newly inserted element.
3270    ///
3271    /// # Safety
3272    ///
3273    /// You must ensure that the `BTreeMap` invariants are maintained.
3274    /// Specifically:
3275    ///
3276    /// * The key of the newly inserted element must be unique in the tree.
3277    /// * All keys in the tree must remain in sorted order.
3278    #[unstable(feature = "btree_cursors", issue = "107540")]
3279    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3280        let edge = match self.current.take() {
3281            None => {
3282                // Tree is empty, allocate a new root.
3283                // SAFETY: We have no other reference to the tree.
3284                let root = unsafe { self.root.reborrow() };
3285                debug_assert!(root.is_none());
3286                let mut node = NodeRef::new_leaf(self.alloc.clone());
3287                // SAFETY: We don't touch the root while the handle is alive.
3288                let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3289                *root = Some(node.forget_type());
3290                *self.length += 1;
3291                self.current = Some(handle.left_edge());
3292                return;
3293            }
3294            Some(current) => current,
3295        };
3296
3297        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3298            drop(ins.left);
3299            // SAFETY: The handle to the newly inserted value is always on a
3300            // leaf node, so adding a new root node doesn't invalidate it.
3301            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3302            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3303        });
3304        self.current = Some(handle.left_edge());
3305        *self.length += 1;
3306    }
3307
3308    /// Inserts a new key-value pair into the map in the gap that the
3309    /// cursor is currently pointing to.
3310    ///
3311    /// After the insertion the cursor will be pointing at the gap after the
3312    /// newly inserted element.
3313    ///
3314    /// # Safety
3315    ///
3316    /// You must ensure that the `BTreeMap` invariants are maintained.
3317    /// Specifically:
3318    ///
3319    /// * The key of the newly inserted element must be unique in the tree.
3320    /// * All keys in the tree must remain in sorted order.
3321    #[unstable(feature = "btree_cursors", issue = "107540")]
3322    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3323        let edge = match self.current.take() {
3324            None => {
3325                // SAFETY: We have no other reference to the tree.
3326                match unsafe { self.root.reborrow() } {
3327                    root @ None => {
3328                        // Tree is empty, allocate a new root.
3329                        let mut node = NodeRef::new_leaf(self.alloc.clone());
3330                        // SAFETY: We don't touch the root while the handle is alive.
3331                        let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3332                        *root = Some(node.forget_type());
3333                        *self.length += 1;
3334                        self.current = Some(handle.right_edge());
3335                        return;
3336                    }
3337                    Some(root) => root.borrow_mut().last_leaf_edge(),
3338                }
3339            }
3340            Some(current) => current,
3341        };
3342
3343        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3344            drop(ins.left);
3345            // SAFETY: The handle to the newly inserted value is always on a
3346            // leaf node, so adding a new root node doesn't invalidate it.
3347            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3348            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3349        });
3350        self.current = Some(handle.right_edge());
3351        *self.length += 1;
3352    }
3353
3354    /// Inserts a new key-value pair into the map in the gap that the
3355    /// cursor is currently pointing to.
3356    ///
3357    /// After the insertion the cursor will be pointing at the gap before the
3358    /// newly inserted element.
3359    ///
3360    /// If the inserted key is not greater than the key before the cursor
3361    /// (if any), or if it not less than the key after the cursor (if any),
3362    /// then an [`UnorderedKeyError`] is returned since this would
3363    /// invalidate the [`Ord`] invariant between the keys of the map.
3364    #[unstable(feature = "btree_cursors", issue = "107540")]
3365    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3366        if let Some((prev, _)) = self.peek_prev() {
3367            if &key <= prev {
3368                return Err(UnorderedKeyError {});
3369            }
3370        }
3371        if let Some((next, _)) = self.peek_next() {
3372            if &key >= next {
3373                return Err(UnorderedKeyError {});
3374            }
3375        }
3376        unsafe {
3377            self.insert_after_unchecked(key, value);
3378        }
3379        Ok(())
3380    }
3381
3382    /// Inserts a new key-value pair into the map in the gap that the
3383    /// cursor is currently pointing to.
3384    ///
3385    /// After the insertion the cursor will be pointing at the gap after the
3386    /// newly inserted element.
3387    ///
3388    /// If the inserted key is not greater than the key before the cursor
3389    /// (if any), or if it not less than the key after the cursor (if any),
3390    /// then an [`UnorderedKeyError`] is returned since this would
3391    /// invalidate the [`Ord`] invariant between the keys of the map.
3392    #[unstable(feature = "btree_cursors", issue = "107540")]
3393    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3394        if let Some((prev, _)) = self.peek_prev() {
3395            if &key <= prev {
3396                return Err(UnorderedKeyError {});
3397            }
3398        }
3399        if let Some((next, _)) = self.peek_next() {
3400            if &key >= next {
3401                return Err(UnorderedKeyError {});
3402            }
3403        }
3404        unsafe {
3405            self.insert_before_unchecked(key, value);
3406        }
3407        Ok(())
3408    }
3409
3410    /// Removes the next element from the `BTreeMap`.
3411    ///
3412    /// The element that was removed is returned. The cursor position is
3413    /// unchanged (before the removed element).
3414    #[unstable(feature = "btree_cursors", issue = "107540")]
3415    pub fn remove_next(&mut self) -> Option<(K, V)> {
3416        let current = self.current.take()?;
3417        if current.reborrow().next_kv().is_err() {
3418            self.current = Some(current);
3419            return None;
3420        }
3421        let mut emptied_internal_root = false;
3422        let (kv, pos) = current
3423            .next_kv()
3424            // This should be unwrap(), but that doesn't work because NodeRef
3425            // doesn't implement Debug. The condition is checked above.
3426            .ok()?
3427            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3428        self.current = Some(pos);
3429        *self.length -= 1;
3430        if emptied_internal_root {
3431            // SAFETY: This is safe since current does not point within the now
3432            // empty root node.
3433            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3434            root.pop_internal_level(self.alloc.clone());
3435        }
3436        Some(kv)
3437    }
3438
3439    /// Removes the preceding element from the `BTreeMap`.
3440    ///
3441    /// The element that was removed is returned. The cursor position is
3442    /// unchanged (after the removed element).
3443    #[unstable(feature = "btree_cursors", issue = "107540")]
3444    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3445        let current = self.current.take()?;
3446        if current.reborrow().next_back_kv().is_err() {
3447            self.current = Some(current);
3448            return None;
3449        }
3450        let mut emptied_internal_root = false;
3451        let (kv, pos) = current
3452            .next_back_kv()
3453            // This should be unwrap(), but that doesn't work because NodeRef
3454            // doesn't implement Debug. The condition is checked above.
3455            .ok()?
3456            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3457        self.current = Some(pos);
3458        *self.length -= 1;
3459        if emptied_internal_root {
3460            // SAFETY: This is safe since current does not point within the now
3461            // empty root node.
3462            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3463            root.pop_internal_level(self.alloc.clone());
3464        }
3465        Some(kv)
3466    }
3467}
3468
3469impl<'a, K: Ord, V, A: Allocator + Clone> CursorMut<'a, K, V, A> {
3470    /// Inserts a new key-value pair into the map in the gap that the
3471    /// cursor is currently pointing to.
3472    ///
3473    /// After the insertion the cursor will be pointing at the gap after the
3474    /// newly inserted element.
3475    ///
3476    /// # Safety
3477    ///
3478    /// You must ensure that the `BTreeMap` invariants are maintained.
3479    /// Specifically:
3480    ///
3481    /// * The key of the newly inserted element must be unique in the tree.
3482    /// * All keys in the tree must remain in sorted order.
3483    #[unstable(feature = "btree_cursors", issue = "107540")]
3484    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3485        unsafe { self.inner.insert_after_unchecked(key, value) }
3486    }
3487
3488    /// Inserts a new key-value pair into the map in the gap that the
3489    /// cursor is currently pointing to.
3490    ///
3491    /// After the insertion the cursor will be pointing at the gap after the
3492    /// newly inserted element.
3493    ///
3494    /// # Safety
3495    ///
3496    /// You must ensure that the `BTreeMap` invariants are maintained.
3497    /// Specifically:
3498    ///
3499    /// * The key of the newly inserted element must be unique in the tree.
3500    /// * All keys in the tree must remain in sorted order.
3501    #[unstable(feature = "btree_cursors", issue = "107540")]
3502    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3503        unsafe { self.inner.insert_before_unchecked(key, value) }
3504    }
3505
3506    /// Inserts a new key-value pair into the map in the gap that the
3507    /// cursor is currently pointing to.
3508    ///
3509    /// After the insertion the cursor will be pointing at the gap before the
3510    /// newly inserted element.
3511    ///
3512    /// If the inserted key is not greater than the key before the cursor
3513    /// (if any), or if it not less than the key after the cursor (if any),
3514    /// then an [`UnorderedKeyError`] is returned since this would
3515    /// invalidate the [`Ord`] invariant between the keys of the map.
3516    #[unstable(feature = "btree_cursors", issue = "107540")]
3517    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3518        self.inner.insert_after(key, value)
3519    }
3520
3521    /// Inserts a new key-value pair into the map in the gap that the
3522    /// cursor is currently pointing to.
3523    ///
3524    /// After the insertion the cursor will be pointing at the gap after the
3525    /// newly inserted element.
3526    ///
3527    /// If the inserted key is not greater than the key before the cursor
3528    /// (if any), or if it not less than the key after the cursor (if any),
3529    /// then an [`UnorderedKeyError`] is returned since this would
3530    /// invalidate the [`Ord`] invariant between the keys of the map.
3531    #[unstable(feature = "btree_cursors", issue = "107540")]
3532    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3533        self.inner.insert_before(key, value)
3534    }
3535
3536    /// Removes the next element from the `BTreeMap`.
3537    ///
3538    /// The element that was removed is returned. The cursor position is
3539    /// unchanged (before the removed element).
3540    #[unstable(feature = "btree_cursors", issue = "107540")]
3541    pub fn remove_next(&mut self) -> Option<(K, V)> {
3542        self.inner.remove_next()
3543    }
3544
3545    /// Removes the preceding element from the `BTreeMap`.
3546    ///
3547    /// The element that was removed is returned. The cursor position is
3548    /// unchanged (after the removed element).
3549    #[unstable(feature = "btree_cursors", issue = "107540")]
3550    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3551        self.inner.remove_prev()
3552    }
3553}
3554
3555/// Error type returned by [`CursorMut::insert_before`] and
3556/// [`CursorMut::insert_after`] if the key being inserted is not properly
3557/// ordered with regards to adjacent keys.
3558#[derive(Clone, PartialEq, Eq, Debug)]
3559#[unstable(feature = "btree_cursors", issue = "107540")]
3560pub struct UnorderedKeyError {}
3561
3562#[unstable(feature = "btree_cursors", issue = "107540")]
3563impl fmt::Display for UnorderedKeyError {
3564    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3565        write!(f, "key is not properly ordered relative to neighbors")
3566    }
3567}
3568
3569#[unstable(feature = "btree_cursors", issue = "107540")]
3570impl Error for UnorderedKeyError {}
3571
3572#[cfg(test)]
3573mod tests;